"""One approved correction may assist masks, but must not become recursive GT."""
import copy
import hashlib
import json

import pytest

from test_pose_review import dataset
from pallet.cluster_targets import digest
from pallet.mask_template_continue import auxiliary_seed
from pallet.pose_review import PoseApplication
from pallet.pose_review_geometry import canonical
from pallet.pose_review_masks import MaskSuggestions


def sha(value):return hashlib.sha256(canonical(value)).hexdigest()


@pytest.fixture
def auxiliary_app(dataset,tmp_path):
    root,source,annotation=dataset
    ss=[dict(source,frame_id='capture/'+name) for name in ('human','seed','target')]
    aa=[dict(annotation,frame_id=s['frame_id']) for s in ss]
    (root/'frames.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in ss))
    (root/'annotations/frames.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in aa))
    app=PoseApplication(root,tmp_path/'reviews',protect=False);app.machine_suggestion=lambda key:None
    keys={app.row(k)['frame_id'].split('/')[-1]:k for k in app.keys}
    polygon=[[2,3],[46,3],[46,22],[39,22],[39,9],[9,9],[9,22],[2,22]]
    upstream=app.save(keys['human'],dict(binding=app.binding,expected_revision=0,polygon=polygon,sensor=app.sensor(keys['human']),reviewer='human'))
    seed_detail=app.detail(keys['seed'])
    seed_review=app.save(keys['seed'],dict(binding=app.binding,expected_revision=0,polygon=seed_detail['initial_polygon'],sensor=app.sensor(keys['seed']),reviewer='human'))
    original=dict(target_key=keys['seed'],source=app.row(keys['seed']),class_id=1,polygon=polygon,
        target_expected_revision=1,target_snapshot_payload_sha256=sha(seed_review),
        template=dict(target_key=keys['human'],current_payload_sha256=sha(upstream)),
        boundary_correction=dict(after=dict(state='passed')))
    outputs=tmp_path/'outputs';outputs.mkdir();configs=tmp_path/'configs';configs.mkdir()
    seed_path=outputs/'seed.jsonl';seed_path.write_bytes(canonical(original)+b'\n')
    seed_config=dict(source_proposals='outputs/seed.jsonl',source_proposals_sha256=digest(seed_path),
        target_key=keys['seed'],source_proposal_sha256=sha(original),polygon_sha256=sha(polygon),
        maximum_auxiliary_hops=1,allow_generated_candidates_as_new_seeds=False)
    seed_config_path=configs/'seed.json';seed_config_path.write_bytes(canonical(seed_config))
    rows={k:dict(app.row(k),final_class_id=1) for k in app.keys}
    t=auxiliary_seed(seed_config,app.store.all(),rows,root=tmp_path)
    p=dict(target_key=keys['target'],source=app.row(keys['target']),class_id=1,polygon=polygon,vertex_count=8,
        formal_manifest_sha256=digest(root/'manifest.json'),target_expected_revision=0,target_snapshot_payload_sha256=None,
        template=dict(target_key=keys['seed'],class_id=1,split='train',vertex_count=8,snapshot_revision=1,
            current_payload_sha256=sha(seed_review),human_polygon_revision=None,template_human_confirmed=False,
            origin=t['origin'],auxiliary_seed=t['auxiliary_seed']),metrics={},mask_semantics='fork_face_notches',
        flags=['auxiliary_seed_not_GT'],snapshot_sha256='fixture')
    ppath=outputs/'proposals.jsonl';config=configs/'active.json'
    active=dict(proposals='outputs/proposals.jsonl',proposals_sha256='',count=1,version=3,
        formal_manifest_sha256=p['formal_manifest_sha256'],auxiliary_seed_config='configs/seed.json',
        auxiliary_seed_config_sha256=digest(seed_config_path))
    def publish(value=p):
        ppath.write_bytes(canonical(value)+b'\n');active['proposals_sha256']=digest(ppath);config.write_bytes(canonical(active))
    publish();app.masks=MaskSuggestions(config,root);app.masks.root=tmp_path
    return app,keys,p,publish,seed_config,rows


def test_approved_seed_keeps_real_rectangle_and_full_dependency_chain(auxiliary_app):
    app,keys,p,_,config,rows=auxiliary_app;before=app.store.all()
    d=app.detail(keys['target']);assert d['mask_suggestion']['polygon']==p['polygon']
    assert d['mask_suggestion']['template']['human_polygon_revision'] is None
    assert not d['mask_suggestion']['template']['template_human_confirmed']
    assert len(app.store.get(keys['seed'])['polygon'])==4 and app.store.all()==before
    assert app.queue({'state':['mask_proposal']})['keys']==[keys['target']]


@pytest.mark.parametrize('which',['human','seed'])
def test_any_upstream_revision_hides_auxiliary_suggestion(auxiliary_app,which):
    app,keys,*_=auxiliary_app;key=keys[which];old=app.store.get(key)
    app.store.save(key,1,dict(old,note='new human edit'))
    assert app.detail(keys['target'])['mask_suggestion'] is None
    assert not app.queue({'state':['mask_proposal']})['keys']


@pytest.mark.parametrize('attack',['hop','claim_gt','source_hash','cross_split','dependency'])
def test_auxiliary_loader_rejects_invalid_provenance(auxiliary_app,attack):
    app,keys,p,publish,*_=auxiliary_app;p=copy.deepcopy(p);t=p['template']
    if attack=='hop':t['auxiliary_seed']['auxiliary_hops']=2
    elif attack=='claim_gt':t['template_human_confirmed']=True
    elif attack=='source_hash':t['auxiliary_seed']['source_proposal_sha256']='0'*64
    elif attack=='cross_split':p['source']['split']='test';t['split']='test'
    else:t['auxiliary_seed']['dependencies']=[]
    publish(p)
    assert app.detail(keys['target'])['mask_suggestion'] is None


def test_auxiliary_adoption_is_unconfirmed_and_retains_provenance(auxiliary_app):
    app,keys,p,*_=auxiliary_app;key=keys['target'];d=app.detail(key);s=d['mask_suggestion']
    value=app.save(key,dict(binding=app.binding,expected_revision=0,polygon=s['polygon'],sensor=d['sensor'],
        reviewer='human',mask_proposal_id=s['proposal_id']))
    assert value['state']=='draft' and not value['human_mask_confirmed'] and not value['automatic_training_eligible']
    assert value['mask_proposal_provenance']['template']['auxiliary_seed']==p['template']['auxiliary_seed']
    assert len(app.store.get(keys['seed'])['polygon'])==4


def test_seed_generation_refuses_new_human_revision(auxiliary_app):
    app,keys,p,publish,config,rows=auxiliary_app
    old=app.store.get(keys['seed']);app.store.save(keys['seed'],1,dict(old,note='do not use old seed'))
    with pytest.raises(ValueError,match='new human revision'):auxiliary_seed(config,app.store.all(),rows,root=app.masks.root)
