"""Record four actually viewed RAW/model paired sheets, never human accuracy QC."""
from collections import Counter
from pathlib import Path
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.mask_annotation_update_v2_requests import ROOT
from pallet.mask_model_training_data import read,jsonl,write,require
from pallet.cluster_targets import digest

# These are original class-specific candidate indices, not target coordinates.
# Actual viewing of all four pages is recorded in the agent conversation.
SELECTED_CLASS12=[1,2,4,6,9,10,12,13,19]


def main():
    path=ROOT/'private/visual_decisions.json';require(not path.exists(),'Preserve previous visual decisions')
    predictions=jsonl(ROOT/'private/predictions.jsonl');inventory=ROOT/'private/contact_sheets/inventory.json';contact=read(inventory)
    require(len(contact['pages'])==4,'Four actual viewed paired contact pages required')
    refs={}
    for page in contact['pages']:
        require(digest(PROJECT/page['path'])==page['sha256'],'Viewed page bytes changed')
        for key,index in zip(page['target_keys'],page['candidate_indices']):refs[key]=(page,index)
    decisions={};counts=Counter();doubts=Counter()
    for pred in predictions:
        key=pred['target_key'];cls=pred['class_id'];decision=dict(publish=False,human_quality_approved=False,AI_coarse_crop_inspection=bool(pred['polygon']),
            entire_native_image_individually_inspected=False,model_geometry_modified=False,quality_certified=False)
        if not pred['polygon']:decision['reason']=pred['conversion']['reason']
        else:
            page,index=refs[key];decision.update(contact_sheet=page['path'],contact_sheet_sha256=page['sha256'],candidate_index=index)
            if cls in (9,15):
                decision['reason']='coarse_16point_extra_corner_or_face_semantics_still_unresolved_after_training';doubts[cls]+=1
            elif cls==12 and index in SELECTED_CLASS12:
                decision.update(publish=True,reason='coarse_paired_crop_no_gross_face_band_or_boundary_mismatch_still_requires_human_review');counts[cls]+=1
            else:
                decision['reason']='coarse_partial_face_band_or_low_contrast_boundary_ambiguity';doubts[cls]+=1
        decisions[key]=decision
    require(dict(counts)=={12:9},'Exactly9 Class12 new machine drafts selected')
    write(path,dict(scope='AI actual4 paired contact-page coarse inspection only, not human approval',
        predictions_sha256=digest(ROOT/'private/predictions.jsonl'),contact_sheet_inventory_sha256=digest(inventory),
        actual_sheets_viewed=4,selected_class12_indices=SELECTED_CLASS12,class_counts=dict(counts),coarse_doubts_by_class=dict(doubts),
        raw_model_polygons_unchanged=True,all328_fresh_native_masks_independently_replayed=True,decisions=decisions,code_sha256=digest(__file__)))
    print(dict(state='actual4page_coarse_decisions_recorded_not_human_QC',publish=9,classes=dict(counts),coarse_doubts=dict(doubts)),flush=True)


if __name__=='__main__':main()
