from copy import deepcopy
from types import SimpleNamespace

import pytest

from pallet.mask_class_keypoint_review import validate_keypoints,editor_js,editable_editor_js,ClassKeypointGallery
from pallet.mask_class_keypoints import VERSION
from pallet.mask_gallery_review import ReviewError
from test_mask_model_worklist import editor,payload,proposal


def fixed(p):
    p['class_keypoint_constraint']=dict(class_id=p['class_id'],standard_count=8,standard_sha256='standard',
        method='unique_class_saved_polygon_vertex_count_mode')
    p['model_provenance']['corner_conversion']=dict(algorithm=VERSION)
    return p


def test_class_standard_validated_in_addition_to_model_provenance():
    p=fixed(proposal());standard=dict(classes={'4':dict(standard_count=8)})
    validate_keypoints(p,standard,'standard');p['polygon']=p['polygon'][:4];p['vertex_count']=4
    with pytest.raises(ValueError):validate_keypoints(p,standard,'standard')


def test_wrong_K_human_save_rejected_without_event(tmp_path):
    e,p=editor(tmp_path);fixed(p);data=payload(p);data['polygon']=[[10,10],[60,10],[60,50],[10,50]]
    with pytest.raises(ReviewError) as error:e.save(p['target_key'],data)
    assert error.value.status==400 and not e.store.summary()


def test_fixed_K_human_save_binds_new_namespace_and_standard(tmp_path):
    e,p=editor(tmp_path);fixed(p);e.gallery.publication_version='model-class-keypoints-v3'
    value=e.save(p['target_key'],payload(p))
    assert value['class_keypoint_constraint']==p['class_keypoint_constraint']
    assert value['proposal_publication']=='model-class-keypoints-v3' and not value['ground_truth_eligible']


def test_browser_retains_drafts_in_a_distinct_namespace_and_blocks_insertion():
    # Historical immutable machine-package JS stays reproducible, while the
    # active human editor is an independent versioned resource.
    js=editor_js()
    assert 'mask-class-keypoints-v3:' in js and 'mask-gallery-v1:' not in js
    assert 'if(detail.class_keypoint_constraint)' in js and 'if(detail?.class_keypoint_constraint)' in js


def editable(tmp_path):
    e,p=editor(tmp_path);fixed(p);e.gallery.publication_version='model-class-keypoints-v3'
    e.gallery.allow_class_keypoint_count_changes=True
    return e,p


def with_extra_point(p):return [p['polygon'][0],[35,10]]+p['polygon'][1:]


def test_active_human_editor_restores_original_edge_insertion_and_local_draft_key():
    js=editable_editor_js()
    assert ClassKeypointGallery.allow_class_keypoint_count_changes is True
    assert 'mask-class-keypoints-v3:' in js and 'mask-gallery-v1:' not in js
    assert 'polygon.splice(edge+1,0,point)' in js and 'polygon.splice(selected,1)' in js
    assert 'if(detail.class_keypoint_constraint)' not in js and 'if(detail?.class_keypoint_constraint)' not in js
    assert 'polygon.length>=128' in js and 'polygon.length<=3' in js


def test_human_can_save_inserted_point_without_changing_initial_class_K(tmp_path):
    e,p=editable(tmp_path);before=deepcopy(p);data=payload(p);data['polygon']=with_extra_point(p)
    value=e.save(p['target_key'],data)
    assert value['vertex_count']==9 and value['original_vertex_count']==8 and p==before
    assert value['class_keypoint_constraint']['standard_count']==8
    assert value['human_keypoint_editing']==dict(policy='human_keypoint_fine_adjustment_add_remove_v1',
        standard_applies_to='initial_machine_proposal_only',initial_standard_count=8,actual_saved_count=9,
        delta_from_standard=1,standard_count_matches=False,previous_saved_or_initial_count=8,point_count_changed_from_previous=True)
    assert not value['ground_truth_eligible'] and not value['automatic_training_eligible']


def test_caller_cannot_forge_count_override_provenance(tmp_path):
    e,p=editable(tmp_path);data=payload(p);data['polygon']=with_extra_point(p)
    data['human_keypoint_editing']=dict(initial_standard_count=9,delta_from_standard=0,standard_count_matches=True)
    data['class_keypoint_constraint']=dict(standard_count=9)
    value=e.save(p['target_key'],data)
    assert value['class_keypoint_constraint']['standard_count']==8
    assert value['human_keypoint_editing']['delta_from_standard']==1


def test_human_count_change_does_not_weaken_machine_proposal_validation(tmp_path):
    e,p=editable(tmp_path);p['polygon']=with_extra_point(p);p['vertex_count']=9
    standard=dict(classes={'4':dict(standard_count=8)})
    with pytest.raises(ValueError):validate_keypoints(p,standard,'standard')


def test_added_count_export_uses_actual_saved_K_points_not_standard_count(tmp_path):
    import json
    e,p=editable(tmp_path);data=payload(p);data['polygon']=with_extra_point(p);saved=e.save(p['target_key'],data)
    raw,_,_=e.export(p['target_key'],'labelme.json');value=json.loads(raw)
    assert value['num_keypoints']==9 and value['initial_standard_keypoint_count']==8
    assert not value['keypoint_count_matches_class_standard']
    assert value['keypoints_xy']==saved['polygon'] and len([s for s in value['shapes'] if s['shape_type']=='point'])==9
    assert value['mask_gallery_review']==saved and value['human_keypoint_editing']==saved['human_keypoint_editing']


def test_variable_point_history_restore_appends_and_records_previous_count(tmp_path):
    e,p=editable(tmp_path);data=payload(p);data['polygon']=with_extra_point(p);first=e.save(p['target_key'],data)
    data.update(expected_revision=1,polygon=p['polygon']);second=e.save(p['target_key'],data)
    assert second['human_keypoint_editing']['previous_saved_or_initial_count']==9
    data.update(expected_revision=2,polygon=first['polygon'],restored_from_revision=1);third=e.save(p['target_key'],data)
    assert third['revision']==3 and third['restored_from_revision']==1 and len(third['polygon'])==9
    assert e.store.history(p['target_key'])[-1]==first
    assert third['human_keypoint_editing']['previous_saved_or_initial_count']==8


def test_added_point_stale_revision_cannot_overwrite_saved_history(tmp_path):
    e,p=editable(tmp_path);first=e.save(p['target_key'],payload(p));data=payload(p);data['polygon']=with_extra_point(p)
    with pytest.raises(ReviewError) as error:e.save(p['target_key'],data)
    assert error.value.status==409 and e.store.get(p['target_key'])==first and len(e.store.history(p['target_key']))==1


@pytest.mark.parametrize('polygon',[
    [[10,10],[60,10]],
    [[10,10],[60,50],[60,10],[10,50]],
    [[-1,10],[60,10],[60,50],[10,50]],
    [[10,10],[float('nan'),10],[60,50],[10,50]],
])
def test_variable_K_still_requires_valid_finite_native_polygon(tmp_path,polygon):
    e,p=editable(tmp_path);data=payload(p);data['polygon']=polygon
    with pytest.raises(ReviewError) as error:e.save(p['target_key'],data)
    assert error.value.status==400 and not e.store.summary()


def test_audit_preserves_legacy_fixed_count_events_and_accepts_traced_new_addition(tmp_path):
    from contextlib import closing
    from pathlib import Path
    from pallet.cluster_targets import digest
    from pallet.pose_review_geometry import canonical
    from pallet.mask_model_review import sha
    from scripts.audit_mask_model_reviews import audit
    root=tmp_path/'worklist';root.mkdir();e,p=editable(tmp_path)
    p['source'].update(frame_id='synthetic frame',split='train',bbox=dict(x=10,y=10,width=50,height=40),source_pcd_sha256='pcd')
    p['formal_manifest_sha256']='formal';p['model_source_image_sha256']='image'
    (root/'proposals.jsonl').write_bytes(canonical(p)+b'\n')
    manifest=dict(source_namespace='model-class-keypoints-v3',actual_human_saved_before={str(c):0 for c in range(1,23)})
    (root/'manifest.json').write_bytes(canonical(manifest)+b'\n');e.gallery.manifest_sha256=digest(root/'manifest.json')
    identity={name:p['source'][name] for name in ('target_key','frame_id','split','box_index','bbox','size','source_pcd_sha256')}
    identity.update(formal_manifest_sha256='formal',image_sha256='image')
    e.identity=lambda key:identity;e.source_binding=lambda key:sha(identity)
    with closing(e.store.connect()) as db:
        db.execute('INSERT OR IGNORE INTO metadata VALUES (?,?)',('worklist_manifest_sha256',e.gallery.manifest_sha256))
        db.execute('INSERT OR IGNORE INTO metadata VALUES (?,?)',('source_namespace','model-class-keypoints-v3'))
    e.gallery.allow_class_keypoint_count_changes=False
    data=payload(p);data['source_binding']=sha(identity);first=e.save(p['target_key'],data)
    assert 'human_keypoint_editing' not in first
    e.gallery.allow_class_keypoint_count_changes=True;data.update(expected_revision=1,polygon=with_extra_point(p))
    second=e.save(p['target_key'],data);result=audit(root,e.store.path)
    assert result['events']==2 and result['new_distinct_saved_images']==1
    assert result['class_human_saved_count_different_from_initial_standard']=={p['class_id']:1}
    assert e.store.history(p['target_key'])[-1]==first
