from types import SimpleNamespace
import hashlib,json
from pathlib import Path
import pytest
from PIL import Image
from pallet.manual_update import merge_reviewed,validate_document
from pallet.human_labeling import _reviewed_external_exclusions,_choose_group_holdout
from pallet.annotation import FrameAnnotation,Box
import pallet.human_labeling as human


def test_checked_reconstruction_priority_is_explicit():
    old={'f':'historical','g':'generic'}
    with pytest.raises(ValueError,match='Unexpected duplicate'):
        merge_reviewed(old,{'f':'checked'},replace_existing=False)
    result,overlap=merge_reviewed(old,{'f':'checked','h':'new'},replace_existing=True)
    assert result=={'f':'checked','g':'generic','h':'new'} and overlap==['f']


def test_correction_does_not_trust_old_pending_flags(tmp_path):
    Image.new('L',(32,24),12).save(tmp_path/'image.png')
    doc={'imageWidth':32,'imageHeight':24,'imagePath':'image.png','flags':{'unreviewed':True},'shapes':[],
         'pallet_prediction':{'frame_id':'f','source_anchor_hash':'h'}}
    (tmp_path/'image.json').write_text(json.dumps(doc))
    row={'frame_id':'f','source_anchor_hash':'h','size':[32,24],'group_id':'g','annotation':'image.json','image':'image.png'}
    record=SimpleNamespace(source_sha256='h',group_id='g')
    assert validate_document(doc,doc,row,tmp_path,record)==[]
    changed={**doc,'pallet_prediction':{'frame_id':'other','source_anchor_hash':'h'}}
    with pytest.raises(ValueError,match='identity'):
        validate_document(changed,doc,row,tmp_path,record)
    changed={**doc,'imageWidth':33}
    with pytest.raises(ValueError,match='dimensions'):
        validate_document(changed,doc,row,tmp_path,record)


def test_external_review_ids_exclude_without_loading_labels(tmp_path,monkeypatch):
    protocol=tmp_path/'protocol';protocol.mkdir();(protocol/'protocol.json').write_text('{}')
    out=tmp_path/'run';(out/'inputs').mkdir(parents=True)
    receipt=out/'inputs/receipt.json';receipt.write_text(json.dumps({'frame_ids':['f']}))
    excluded=out/'inputs/reviewed_external_exclusion.json'
    excluded.write_text(json.dumps({'frame_ids':['f'],'protocol_sha256':human.file_digest(protocol/'protocol.json'),
        'receipt_path':'inputs/receipt.json','receipt_sha256':human.file_digest(receipt)}))
    records=[SimpleNamespace(frame_id='f',group_id='g')]
    monkeypatch.setattr(human,'load_protocol',lambda _: (records,{'g':'test'},{}))
    assert _reviewed_external_exclusions(out,protocol)[0]=={'f'}
    receipt.write_text(json.dumps({'frame_ids':['other']}))
    with pytest.raises(ValueError,match='receipt changed'):
        _reviewed_external_exclusions(out,protocol)


def test_single_negative_group_stays_intact_in_training():
    frames=[]; records={}
    for g in range(4):
        fid=f'f{g}'
        f=FrameAnnotation(fid,f'g{g}','none',32,24,status='negative' if g==0 else 'pos',boxes=[] if g==0 else [Box(1,1,4,4)],source_anchor_hash=f'h{g}',domain='d')
        frames.append(f);records[fid]=SimpleNamespace(frame_id=fid,group_id=f.group_id,source_sha256=f.source_anchor_hash,domain='d')
    val,groups,summary=_choose_group_holdout(frames,records,seed=42,fraction=.15)
    assert 'f0' not in val and summary['d']['negative_stratification_feasible'] is False
    assert summary['d']['training_negatives']==1 and summary['d']['validation_negatives']==0
