from copy import deepcopy
from pathlib import Path

import pytest

from pallet.mask_annotation_update_review import validate,editor_js,UpdatedKeypointGallery
from pallet.mask_annotation_update_requests import SCHEMA,NAMESPACE,DRAFT_PREFIX
from pallet.mask_class_keypoints import VERSION
from pallet.mask_gallery_review import ReviewError
from test_mask_model_worklist import editor,payload,proposal


def updated(p):
    p.update(schema=SCHEMA,origin='updated_M2_prediction')
    p['source']['final_class_id']=p['class_id']
    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)
    p['model_provenance']['quality_gate_passed']=False
    return p


def test_new_machine_validator_binds_updated_checkpoint_and_class_K():
    p=updated(proposal());s=dict(classes={'4':dict(standard_count=8)})
    validate(p,s,'standard',p['model_provenance']['checkpoint_sha256'])
    with pytest.raises(ValueError):validate(p,s,'standard','old-or-different-model')
    with pytest.raises(ValueError):validate(p,s,'wrong-standard',p['model_provenance']['checkpoint_sha256'])
    p['polygon']=p['polygon'][:4];p['vertex_count']=4
    with pytest.raises(ValueError):validate(p,s,'standard',p['model_provenance']['checkpoint_sha256'])


@pytest.mark.parametrize('field',['human_edited','ground_truth_eligible','automatic_training_eligible','counts_as_completed_annotation'])
def test_no_machine_auto_promotion(field):
    p=updated(proposal());p[field]=True
    with pytest.raises(ValueError):validate(p,dict(classes={'4':dict(standard_count=8)}),'standard',p['model_provenance']['checkpoint_sha256'])


def test_new_namespace_keeps_original_human_add_delete_and_does_not_touch_old_drafts():
    js=editor_js()
    assert DRAFT_PREFIX in js and 'mask-class-keypoints-v3:' not 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
    assert UpdatedKeypointGallery.publication_namespace==NAMESPACE and UpdatedKeypointGallery.allow_class_keypoint_count_changes


def test_new_namespace_manual_added_points_saved_and_exported_without_machine_change(tmp_path):
    import json
    e,p=editor(tmp_path);updated(p);before=deepcopy(p)
    e.gallery.publication_version=NAMESPACE;e.gallery.allow_class_keypoint_count_changes=True
    e.gallery.validate=lambda value:validate(value,dict(classes={'4':dict(standard_count=8)}),'standard',p['model_provenance']['checkpoint_sha256'])
    data=payload(p);data['polygon']=[p['polygon'][0],[35,10]]+p['polygon'][1:]
    first=e.save(p['target_key'],data)
    assert first['proposal_publication']==NAMESPACE and first['vertex_count']==9 and p==before
    assert first['human_keypoint_editing']['delta_from_standard']==1 and not first['ground_truth_eligible']
    label=json.loads(e.export(p['target_key'],'labelme.json')[0])
    assert label['num_keypoints']==9 and label['initial_standard_keypoint_count']==8
    with pytest.raises(ReviewError) as error:e.save(p['target_key'],data)
    assert error.value.status==409 and len(e.store.history(p['target_key']))==1


def test_update_audit_base_count_comes_from_manifest_not_old1559(tmp_path):
    import json
    from scripts.audit_mask_model_reviews import audit
    # An empty genuine-shaped store is enough to catch the prior hardcoded
    # baseline count; no synthetic polygon is added to a real source store.
    from pallet.mask_gallery_review import MaskReviewStore
    from pallet.cluster_targets import digest
    from contextlib import closing
    root=tmp_path/'requests';root.mkdir();(root/'proposals.jsonl').write_text('')
    (root/'manifest.json').write_text(json.dumps(dict(source_namespace=NAMESPACE,base_manual_count=1896,
        actual_human_saved_before={str(c):1 for c in range(1,23)})))
    store=MaskReviewStore(tmp_path/'reviews','formal')
    with closing(store.connect()) as db:
        db.execute('INSERT INTO metadata VALUES (?,?)',('worklist_manifest_sha256',digest(root/'manifest.json')))
        db.execute('INSERT INTO metadata VALUES (?,?)',('source_namespace',NAMESPACE));db.commit()
    result=audit(root,store.path)
    assert result['base_manual_count']==1896 and result['new_distinct_saved_images']==0 and not result['automatic_training_or_GT_promotion']


def test_serve_uses_a_separate_port_store_and_accepts_only_added_point_browser_evidence():
    import scripts.serve_mask_annotation_update_requests as service
    assert service.PORT==3407 and service.REVIEWS.name=='pallet_mask_model_reviews_v4'
    text=Path(service.__file__).read_text()
    assert 'human_added_point_save_and_reload' in text and 'stale_tab_409_preserves_local_draft' in text
    assert '127.0.0.1' in text and '0.0.0.0' not in text
