"""Model provenance, representability, protection and isolated save contracts."""
from copy import deepcopy
from pathlib import Path
from types import SimpleNamespace

import numpy as np
import pytest

from pallet.mask_model_worklist import polygonize,validate_proposal,SCHEMA,CHECKPOINT_SHA,FLAGS
from pallet.mask_model_review import ModelMaskEditor,sha
from pallet.mask_gallery_review import MaskReviewStore,ReviewError
from pallet.pose_review_geometry import raster_mask


def proposal():
    return dict(schema=SCHEMA,origin='model_prediction',status='model_preannotated_pending_human_review',
        target_key='a'*24,class_id=4,source=dict(target_key='a'*24,size=[100,80],box_index=0),
        polygon=[[10,10],[60,10],[60,50],[40,50],[40,25],[20,25],[20,50],[10,50]],vertex_count=8,
        model_provenance=dict(checkpoint_sha256=CHECKPOINT_SHA,model_family='RF-DETR-Seg Small',human_saved=False),
        mask_semantics='machine_draft_not_GT',**dict.fromkeys(FLAGS,False))


def test_pixel_cell_polygon_reconstruction_preserves_concave_notch():
    mask=np.zeros((50,100),bool);mask[10:40,5:95]=1;mask[20:40,20:80]=0
    polygon,metrics=polygonize(mask)
    assert polygon and len(polygon)>=8 and metrics['polygon_vs_model_mask_iou']>=.99
    assert np.array_equal(raster_mask(polygon,100,50),mask)


def test_valid_four_corners_are_not_forced_to_eight():
    mask=np.zeros((40,60),bool);mask[5:30,7:50]=1
    p,m=polygonize(mask);assert len(p)==4


def test_closed_holes_never_silently_filled():
    mask=np.zeros((50,70),bool);mask[5:45,5:65]=1;mask[15:30,20:40]=0
    p,m=polygonize(mask);assert p is None and m['reason']=='closed_model_holes_not_single_ring'


def test_disjoint_components_never_discarded_to_fake_good_polygon():
    mask=np.zeros((50,70),bool);mask[5:20,5:20]=1;mask[30:40,40:50]=1
    p,m=polygonize(mask);assert p is None and m['reason']=='multiple_disconnected_model_components'


def test_empty_prediction_is_not_original_box():
    p,m=polygonize(np.zeros((20,50),bool));assert p is None and m['reason']=='empty_model_mask'


@pytest.mark.parametrize('field',FLAGS)
def test_machine_candidate_never_promoted_by_a_flag(field):
    p=proposal();p[field]=True
    with pytest.raises(ValueError):validate_proposal(p)


def test_real_model_schema_cannot_masquerade_as_assistant_handdrawn():
    p=proposal();validate_proposal(p);p['origin']='assistant_visual_preannotation'
    with pytest.raises(ValueError):validate_proposal(p)


def editor(tmp_path):
    e=object.__new__(ModelMaskEditor);p=proposal();e.proposals={p['target_key']:p};e.binding='binding'
    e.gallery=SimpleNamespace(manifest_sha256='model-manifest');e.source_binding=lambda key:'source'
    e.identity=lambda key:dict(target_key=key);e.proposal_dependency_current=lambda key:True
    e.store=MaskReviewStore(tmp_path/'model-reviews','formal');return e,p


def payload(p):return dict(binding='binding',source_binding='source',proposal_id=sha(p),expected_revision=0,
    polygon=p['polygon'],reviewer='real user',note='review')


def test_model_save_has_exact_model_task_target_provenance_and_no_GT(tmp_path):
    e,p=editor(tmp_path);data=payload(p);data.update(dict.fromkeys(FLAGS,True));r=e.save(p['target_key'],data)
    assert r['event_kind']=='human_model_mask_review' and r['model_provenance']==p['model_provenance']
    assert r['proposal_publication']=='model-native-v1' and r['worklist_manifest_sha256']=='model-manifest'
    assert r['human_edited'] is True and not r['ground_truth_eligible'] and not r['automatic_training_eligible']
    assert r['proposal_polygon']==p['polygon'] and r['base_proposal_id']==sha(p)


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


def test_changed_external_target_rejects_stale_candidate(tmp_path):
    e,p=editor(tmp_path);e.proposal_dependency_current=lambda key:False
    with pytest.raises(ReviewError) as error:e.save(p['target_key'],payload(p))
    assert error.value.status==409 and not e.store.summary()


def test_cannot_route_model_writes_into_old_production_gallery():
    from pallet.mask_model_review import PROJECT
    with pytest.raises(ValueError,match='separate'):
        ModelMaskEditor(None,PROJECT/'outputs/pallet_mask_gallery_reviews_v1','x'*32)


def test_history_restore_appends_instead_of_deleting(tmp_path):
    e,p=editor(tmp_path);first=e.save(p['target_key'],payload(p));data=payload(p)
    data.update(expected_revision=1,polygon=[[10,10],[60,10],[60,50],[10,50]])
    e.save(p['target_key'],data);data.update(expected_revision=2,polygon=p['polygon'],restored_from_revision=1)
    r=e.save(p['target_key'],data);assert r['revision']==3 and r['restored_from_revision']==1 and e.store.history(p['target_key'])[-1]==first


def test_model_target_and_native_image_target_cannot_differ():
    p=proposal();p['target_key']='b'*24
    with pytest.raises(ValueError):validate_proposal(p)


def test_manual_save_does_not_pretend_unchanged_prediction_was_redrawn(tmp_path):
    e,p=editor(tmp_path);value=e.save(p['target_key'],payload(p))
    assert value['human_review_save_action'] is True and value['accepted_model_without_geometry_change'] is True
    assert value['geometry_changed_from_model'] is False


def test_actual_geometry_edit_is_distinguished_from_accepting_model(tmp_path):
    e,p=editor(tmp_path);data=payload(p);data['polygon']=[[10,10],[60,10],[60,50],[10,50]]
    value=e.save(p['target_key'],data)
    assert value['geometry_changed_from_model'] is True and value['accepted_model_without_geometry_change'] is False


def test_changed_native_source_cannot_overwrite_previous_target_history(tmp_path):
    e,p=editor(tmp_path);first=e.save(p['target_key'],payload(p));e.source_binding=lambda key:'different-source'
    data=payload(p);data.update(expected_revision=1,source_binding='different-source')
    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
