"""Saved prelabel corrections stay gallery sources, not fake pose edits/templates."""
import hashlib

import pytest

from pallet.mask_gallery_review import ReviewError
from pallet.pose_review_geometry import canonical
from test_mask_gallery_review import editable,gallery_data,payload,KEY


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


@pytest.fixture
def saved_gallery_entry(editable):
    editor=editable.editor;proposal=editor.proposals[KEY];data=payload(editor)
    data['polygon']=[[2,4],[22,3],[21,21],[3,20]]
    saved=editor.save(KEY,data)
    proposal.pop('template');proposal.update(schema='saved_gallery_mask_entry_v1',origin='mask_gallery_human_revision',
        human_edited=True,manual_four_point_source=True,propagation_seed_eligible=False,polygon=saved['polygon'],vertex_count=4,
        human_source=dict(origin='mask_gallery_human_revision',target_key=KEY,gallery_review=dict(target_key=KEY,
            revision=saved['revision'],source_binding=saved['source_binding'],payload_sha256=sha(saved),polygon_sha256=sha(saved['polygon']))),
        human_mask_confirmed=False,human_pose_confirmed=False,ground_truth_eligible=False,automatic_training_eligible=False,robot_command_eligible=False)
    return editor,proposal,saved


def test_saved_quad_is_not_labelled_machine_pose_or_template(saved_gallery_entry):
    editor,proposal,saved=saved_gallery_entry;detail=editor.detail(KEY)
    assert detail['saved_gallery_manual_source'] and not detail['saved_pose_manual_source']
    assert not detail['assistant_preannotation_source'] and detail['template'] is None
    assert detail['human_source']['gallery_review']['payload_sha256']==sha(saved)
    assert detail['review']==saved and len(detail['history'])==1 and not detail['proposal_dependency_stale']


def test_revision_after_migration_is_appended_and_old_event_preserved(saved_gallery_entry):
    editor,proposal,saved=saved_gallery_entry;before=editor.store.history(KEY)
    data=payload(editor);data['polygon']=[[3,4],[21,3],[21,20],[3,19]]
    result=editor.save(KEY,data)
    assert result['revision']==2 and editor.store.history(KEY)[1:]==before
    assert result['human_source_provenance']==proposal['human_source'] and result['template_provenance'] is None
    assert not result['pose_store_written'] and not result['human_mask_confirmed']
    detail=editor.detail(KEY);assert detail['review']==result and detail['proposal_dependency_stale']


@pytest.mark.parametrize('field,value',[('origin','original_pose_human_revision'),('human_edited',False),('propagation_seed_eligible',True),
    ('manual_four_point_source',False),('vertex_count',8),('human_mask_confirmed',True),('ground_truth_eligible',True)])
def test_invalid_saved_gallery_claims_rejected_without_history_writes(saved_gallery_entry,field,value):
    editor,proposal,saved=saved_gallery_entry;before=editor.store.history(KEY);proposal[field]=value
    with pytest.raises(ReviewError):editor.detail(KEY)
    assert editor.store.history(KEY)==before


def test_wrong_source_or_polygon_binding_cannot_become_a_template(saved_gallery_entry):
    editor,proposal,_=saved_gallery_entry;proposal['human_source']['gallery_review']['polygon_sha256']='0'*64
    with pytest.raises(ReviewError):editor.detail(KEY)
