from copy import deepcopy
from types import SimpleNamespace
import json

import pytest

from pallet.mask_quality_override import template_for,POLICY,GAPS,NAMESPACE,SCHEMA,CHECKPOINT,DRAFT_PREFIX
from pallet.mask_quality_override_review import CorrectionEditor,CorrectionGallery,validate,editor_js
from pallet.mask_gallery_review import ReviewError
from test_mask_model_worklist import editor,payload,proposal


def correction(tmp_path,template):
    e,p=editor(tmp_path);e.__class__=CorrectionEditor
    init=dict(kind='same_class_template',not_this_image_model_geometry=True,template_target_key='b'*24,quality_certified=False) if template else dict(kind='model_class_K',not_this_image_model_geometry=False,quality_certified=False)
    p.update(schema=SCHEMA,origin='same_class_template_initialization' if template else 'unfiltered_M2_model_initialization',
        initialization=init,quality_override_authorized=True,quality_certified=False,image_reuse=dict(counts_as_new_distinct_image=False))
    p['source']['final_class_id']=p['class_id']
    p['class_keypoint_constraint']=dict(class_id=4,standard_count=8,standard_sha256='standard',method='unique_class_saved_polygon_vertex_count_mode')
    p['model_provenance'].update(checkpoint_sha256=CHECKPOINT,initialization=init,quality_gate_passed=False)
    e.gallery.publication_version=NAMESPACE;e.gallery.allow_class_keypoint_count_changes=True
    e.gallery.validate=lambda p:validate(p,dict(classes={'4':dict(standard_count=8)}),'standard')
    return e,p


def test_authorized150_scope_and_no_human_or_GT_override():
    assert sum(GAPS.values())==150 and GAPS[19]==50
    assert POLICY['allow_seen_or_duplicate_images_for_unedited_targets'] and POLICY['template_fallback_not_this_image_model_geometry']
    assert POLICY['protect_completed_deleted_deferred_confirmed_isolated_and_all_human_contour_targets']
    assert POLICY['duplicated_images_never_counted_as_new_distinct_images']


def test_standard_template_is_same_class_real_contour_transformed_without_padding():
    source=proposal();ref=dict(target_key='c'*24,class_id=4,polygon=source['polygon'],source_payload_sha256='raw',source_event_raw_sha256='event')
    row=dict(final_class_id=4,bbox=dict(x=20,y=15,width=50,height=30),size=[100,80])
    polygon,proof=template_for(row,8,[ref]);assert len(polygon)==8 and proof['not_this_image_model_geometry']
    assert proof['template_target_key']==ref['target_key'] and proof['template_class_id']==4
    assert min(x for x,y in polygon)==20 and max(x for x,y in polygon)==70
    assert min(y for x,y in polygon)==15 and max(y for x,y in polygon)==45
    assert not proof['quality_certified']


def test_no_template_from_other_class_or_wrong_K():
    row=dict(final_class_id=19,bbox=dict(x=0,y=0,width=50,height=20),size=[100,80])
    with pytest.raises(ValueError):template_for(row,8,[dict(class_id=4,polygon=proposal()['polygon'])])


@pytest.mark.parametrize('template',[True,False])
def test_initialization_source_must_be_truthful_without_geometry_quality_gate(tmp_path,template):
    e,p=correction(tmp_path,template);e.validate(p)
    p['origin']='model_prediction'
    with pytest.raises(ValueError):e.validate(p)


@pytest.mark.parametrize('field',['ground_truth_eligible','counts_as_completed_annotation','automatic_training_eligible','human_mask_confirmed'])
def test_relaxed_quality_cannot_promote_machine_eligibility(tmp_path,field):
    e,p=correction(tmp_path,True);p[field]=True
    with pytest.raises(ValueError):e.validate(p)


def test_initial_K_still_required_even_when_quality_screen_bypassed(tmp_path):
    e,p=correction(tmp_path,True);p['polygon']=p['polygon'][:4];p['vertex_count']=4
    with pytest.raises(ValueError):e.validate(p)


@pytest.mark.parametrize('template',[True,False])
def test_human_add_point_save_preserves_model_template_and_duplicate_provenance(tmp_path,template):
    e,p=correction(tmp_path,template);before=deepcopy(p);data=payload(p);data['polygon']=[p['polygon'][0],[35,10]]+p['polygon'][1:]
    value=e.save(p['target_key'],data)
    assert value['template_initialized']==template and value['initialization_provenance']==p['initialization'] and value['image_reuse']==p['image_reuse']
    assert value['geometry_changed_from_initialization'] and value['vertex_count']==9 and p==before
    assert value['human_keypoint_editing']['delta_from_standard']==1 and not value['quality_certified'] and not value['automatic_training_eligible']
    assert value['geometry_changed_from_model']==(not template) and not value['accepted_model_without_geometry_change']
    export=json.loads(e.export(p['target_key'],'labelme.json')[0])
    assert export['num_keypoints']==9 and export['initial_standard_keypoint_count']==8 and export['initialization']==p['initialization']
    assert export['image_reuse']==p['image_reuse'] and export['quality_certified'] is False


def test_unchanged_template_save_never_claims_model_accepted_without_edit(tmp_path):
    e,p=correction(tmp_path,True);value=e.save(p['target_key'],payload(p))
    assert not value['accepted_model_without_geometry_change'] and value['accepted_initialization_without_geometry_change']
    assert value['template_initialized'] and not value['geometry_changed_from_initialization']


def test_stale_or_changed_source_still_cannot_overwrite_human_history(tmp_path):
    e,p=correction(tmp_path,True);first=e.save(p['target_key'],payload(p))
    with pytest.raises(ReviewError) as err:e.save(p['target_key'],payload(p))
    assert err.value.status==409 and len(e.store.history(p['target_key']))==1
    e.proposal_dependency_current=lambda key:False;data=payload(p);data['expected_revision']=1
    with pytest.raises(ReviewError):e.save(p['target_key'],data)
    assert e.store.get(p['target_key'])==first


def test_restore_is_append_only_and_keeps_template_attribution(tmp_path):
    e,p=correction(tmp_path,True);first=e.save(p['target_key'],payload(p));data=payload(p);data.update(expected_revision=1,polygon=[p['polygon'][0],[35,10]]+p['polygon'][1:])
    e.save(p['target_key'],data);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['template_initialized'] and third['restored_from_revision']==1
    assert e.store.history(p['target_key'])[-1]==first


def test_new_editor_makes_template_and_duplicate_warning_visible_and_retains_add_delete():
    js=editor_js();assert DRAFT_PREFIX in js and 'mask-class-keypoints-v3:' not in js
    assert '模板占位' in js and '不是本图模型轮廓' in js and '已见/重复图像' in js
    assert 'polygon.splice(edge+1,0,point)' in js and 'polygon.splice(selected,1)' in js
    assert CorrectionGallery.editor_class is CorrectionEditor and CorrectionGallery.allow_class_keypoint_count_changes


def test_runtime_isolated_from_original_supervisor_module():
    from scripts import serve_mask_quality_override as service
    from scripts import serve_mask_annotation_update_v2_requests as original
    assert service.PORT==3409 and service.REVIEWS.name=='pallet_mask_model_reviews_v6'
    assert original.PORT==3408 and original.REVIEWS.name=='pallet_mask_model_reviews_v5'
    assert service.runtime is not original and service.runtime.ModelMaskHandler.__name__=='CorrectionHandler'


def test_export_import_hook_does_not_exist_on_old_model_editor(tmp_path):
    e,p=editor(tmp_path);assert not hasattr(e,'prepare_saved_value');saved=e.save(p['target_key'],payload(p))
    assert 'initialization_provenance' not in saved and saved['accepted_model_without_geometry_change']


def test_read_only_event_audit_accepts_truthful_template_not_fake_model_acceptance(tmp_path):
    from contextlib import closing
    from pallet.pose_review_geometry import canonical
    from pallet.cluster_targets import digest
    from pallet.mask_model_review import sha
    from scripts.audit_mask_model_reviews import audit
    e,p=correction(tmp_path,True);p['source'].update(frame_id='synthetic frame',split='train',bbox=dict(x=10,y=10,width=50,height=40),source_pcd_sha256='pcd')
    p.update(formal_manifest_sha256='formal',model_source_image_sha256='image')
    root=tmp_path/'worklist';root.mkdir();(root/'proposals.jsonl').write_bytes(canonical(p)+b'\n')
    (root/'manifest.json').write_bytes(canonical(dict(source_namespace=NAMESPACE,allow_template_initialization=True,
        actual_human_saved_before={str(c):0 for c in range(1,23)},base_manual_count=2050))+b'\n')
    e.gallery.manifest_sha256=digest(root/'manifest.json')
    identity={k:p['source'][k] for k 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 INTO metadata VALUES (?,?)',('worklist_manifest_sha256',e.gallery.manifest_sha256))
        db.execute('INSERT INTO metadata VALUES (?,?)',('source_namespace',NAMESPACE));db.commit()
    data=payload(p);data['source_binding']=sha(identity);first=e.save(p['target_key'],data)
    assert first['accepted_initialization_without_geometry_change'] and not first['accepted_model_without_geometry_change']
    data.update(expected_revision=1,polygon=[p['polygon'][0],[35,10]]+p['polygon'][1:]);e.save(p['target_key'],data)
    result=audit(root,e.store.path)
    assert result['events']==2 and result['new_distinct_saved_images']==1 and result['base_manual_count']==2050
