"""Independent latest-note/actual-human-polygon/scope replay, not annotation quality."""
from collections import Counter
from contextlib import closing
import hashlib
import json
from pathlib import Path
import re
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.mask_class_note_corrections import ROOT
from pallet.mask_class_correction import ROOT as CLASS_ROOT,STATE as CLASS_STATE
from pallet.mask_class_correction_review import compute,review_signatures
from pallet.mask_model_training_data import read,write,jsonl,require
from pallet.mask_template_refined import readonly
from pallet.mask_quality_recovery import fingerprint
from pallet.cluster_targets import digest
from pallet.pose_review_geometry import canonical,polygon_value


def verify():
    require(not (ROOT/'verification.json').exists(),'Preserve note correction structural seal')
    m=read(ROOT/'manifest.json');deps=read(ROOT/'private/dependencies.json');tasks=jsonl(ROOT/'tasks.jsonl');classes=read(ROOT/'classes.json')
    require(digest(ROOT/'tasks.jsonl')==m['tasks_sha256'] and digest(ROOT/'private/dependencies.json')==m['dependencies_sha256'],'Task/dependency binding differs')
    with closing(readonly(ROOT/'private/class_reviews.sqlite3')) as db:
        row=db.execute("SELECT revision,payload FROM reviews WHERE target_key='class_graph'").fetchone()
        history=list(db.execute("SELECT revision,payload FROM events WHERE target_key='class_graph' ORDER BY revision"))
    require(row and row==history[-1] and row[0]==m['source_class_graph_revision']==421,'Expected completed class snapshot differs')
    require([hashlib.sha256(raw.encode()).hexdigest() for _,raw in history]==deps['old_class_events_sha256'] and hashlib.sha256(row[1].encode()).hexdigest()==deps['class_graph_raw_sha256'],'Frozen raw class history differs')
    with closing(readonly(CLASS_STATE/'mask_reviews.sqlite3')) as db:current=db.execute("SELECT revision,payload FROM reviews WHERE target_key='class_graph'").fetchone()
    require(row==current,'Current finished class/attribute source changed')
    records={r['target_key']:r for r in jsonl(CLASS_ROOT/'private/records.jsonl')};state=json.loads(row[1])['state'];groups,_=compute(list(records.values()),state);signatures=review_signatures(state,groups)
    require(len(groups)==47 and len(records)==2200 and all(state['group_status'].get(f)=='confirm' for f in groups),'All47 final groups must be confirmed')
    current_notes={}
    for revision,raw in reversed(history):
        h=json.loads(raw);face=h.get('face_id')
        if face not in groups or face in current_notes or h['action']!='confirm':continue
        old,_=compute(list(records.values()),h['state'])
        if face not in old or review_signatures(h['state'],old)[face]!=signatures[face]:continue
        current_notes[face]=(h,raw)
    marked={}
    for face,g in groups.items():
        h,raw=current_notes[face];cls=g['proposed_class_id'];frozen=classes[str(cls)]
        require(frozen['full_review_note']==h['note'] and frozen['note_revision']==h['revision'] and frozen['note_event_raw_sha256']==hashlib.sha256(raw.encode()).hexdigest(),'Latest per-group note was not preserved')
        match=re.search(r'(?:^|\n)\s*注\s*[：:]\s*(.*)',h['note'],re.S)
        if match:marked[cls]=match[1].strip()
    require(set(marked)=={12,15,37,47,85,108,124},'Unexpected current 注 class scope')
    expected={12:(4,12,12,'reannotate'),85:(4,12,85,'reannotate'),108:(5,4,14,'reannotate_and_move'),124:(9,8,115,'reannotate_and_move'),
        37:(12,None,None,'exclude'),47:(14,16,9,'occlusion')}
    require(m['informational_note_classes']==[15] and classes['15']['instruction']['kind']=='comparison_only','Class15 structural distinction must not become an error/exclusion')
    expected_keys={key for key,r in records.items() if groups[state['assignments'][key]]['proposed_class_id'] in expected}
    require(len(tasks)==len({p['target_key'] for p in tasks})==90 and {p['target_key'] for p in tasks}==expected_keys,'Exactly all90 noted problem targets required')
    for p in tasks:
        key=p['target_key'];r=records[key];cls=groups[state['assignments'][key]]['proposed_class_id'];oldk,newk,newclass,kind=expected[cls]
        require(p['polygon']==r['polygon'] and p['source']==r['row'] and p['source_revision']==r['source_revision'] and p['source_event_raw_sha256']==r['source_event_raw_sha256'],'Not the actual saved human polygon/source')
        require(p['class_id']==cls and p['actual_K']==len(p['polygon'])==oldk and p['expected_K']==newk and p['target_class_id']==newclass and p['kind']==kind,'Incorrect note action/K/Class interpretation')
        require(p['class_note']['annotation']==marked[cls] and p['class_note']['full_review_note']==classes[str(cls)]['full_review_note'],'Wrong current note association')
        require(p['source_polygon_sha256']==hashlib.sha256(canonical(r['polygon'])).hexdigest() and digest(ROOT/'images'/f'{key}.png')==r['image_sha256'],'Polygon/image bytes changed')
        polygon_value(p['polygon'],*p['source']['size'])
    require(Counter(p['class_id'] for p in tasks)==Counter({12:75,85:11,108:1,124:1,37:1,47:1}),'Per-Class scope differs')
    for p,h in deps['human_source_fingerprints'].items():require(fingerprint(PROJECT/p)==h,'Original human store changed')
    for name,h in m['public_assets'].items():
        path=ROOT/name;require(path.resolve().is_relative_to(ROOT) and not path.is_symlink() and digest(path)==h,'Public source/UI asset changed')
    receipt=dict(state='passed_note_source_scope_and_editor_binding_not_correction_quality',manifest_sha256=digest(ROOT/'manifest.json'),
        source_graph_revision=421,source_groups=47,all2200_source_targets_confirmed=True,current_issue_classes=sorted(expected),targets=90,
        informational_Class15_not_edited=True,older_superseded_annotation_notes_not_reopened=True,original_class_attributes_and_all421_events_preserved=True,
        latest_human_polygons_and_images_verified=True,no_K_resampling_or_occluded_point_invention=True,no_annotation_save_or_exclusion_by_agent=True,
        classification_or_correction_accuracy=None,code_sha256=digest(__file__))
    write(ROOT/'verification.json',receipt);print(json.dumps(receipt),flush=True)


if __name__=='__main__':verify()
