"""Record the actually viewed24 paired sheets; no human-QC or geometry claims."""
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_requests import ROOT
from pallet.mask_model_training_data import read,jsonl,write,require
from pallet.cluster_targets import digest

# Indices refer to the original class-specific paired RAW / model contact pages.
# All24 pages were viewed in the agent conversation; no entire-native-image or
# human-QC claim is made. Keep extra coarse candidates private rather than issue
# more tasks than the actual class gap.
SELECTED={
    1:[1,2,3,4],
    2:[1,2,3,4,5,6,10,11,12,13],
    4:[1,2,4,7,10,11,12,13,15],
    5:list(range(1,22)),
    7:[1,3,4,5,6,7,8,9,10,11,12,13,14,16,18,20,21,22,23],
    10:[1],11:[1,2,3,4,5],
    12:[1,3,4,5,6,7,8,11,14,15,16,19],
    16:[1,2,3],18:list(range(1,13)),20:list(range(1,27)),
    21:list(range(1,22))+[23,24],
}
DOUBTS={
    2:{7,8,9,14,16,17,18,19,20,21,22,23,24,25,26,27,29,30,31,32,33},
    7:{2,15,24,26,33,50},
    12:{2,9,10,12,13,17,18,20,21},
    21:{22,29,37},
}


def main():
    path=ROOT/'private/visual_decisions.json';require(not path.exists(),'Preserve previous actual coarse decisions')
    predictions=jsonl(ROOT/'private/predictions.jsonl');inventory=ROOT/'private/contact_sheets/inventory.json';contact=read(inventory)
    require(len(contact['pages'])==24,'Expected24 actually viewed contact pages')
    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();coarse_doubts=Counter()
    for p in predictions:
        key=p['target_key'];cls=p['class_id'];decision=dict(publish=False,human_quality_approved=False,
            AI_coarse_crop_inspection=bool(p['polygon']),entire_native_image_individually_inspected=False,
            model_geometry_modified=False,quality_certified=False)
        if not p['polygon']:decision['reason']=p['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_unresolved_not_safe_to_publish';coarse_doubts[cls]+=1
            elif index in DOUBTS.get(cls,set()):
                decision['reason']='coarse_partial_face_band_or_viewpoint_boundary_ambiguity';coarse_doubts[cls]+=1
            elif index in SELECTED.get(cls,[]):
                decision.update(publish=True,reason='coarse_paired_crop_has_no_gross_face_or_corner_mismatch_still_requires_human_review');counts[cls]+=1
            else:decision['reason']='not_issued_extra_candidate_beyond_remaining_quota_or_preferred_clearer_crop'
        decisions[key]=decision
    require(sum(counts.values())==145,'Recorded selected145 draft scope differs')
    write(path,dict(scope='AI actual24 paired contact-page coarse inspection only, never human accuracy approval',
        predictions_sha256=digest(ROOT/'private/predictions.jsonl'),contact_sheet_inventory_sha256=digest(inventory),
        actual_sheets_viewed=24,selected_indices_by_class=SELECTED,class_counts=dict(counts),coarse_doubts_by_class=dict(coarse_doubts),
        raw_model_polygons_unchanged=True,all_fresh_native_masks_replayed=True,decisions=decisions,code_sha256=digest(__file__)))
    print(dict(state='actual_coarse_decisions_recorded_not_human_QC',publish=145,classes=dict(counts),coarse_doubts=dict(coarse_doubts)),flush=True)


if __name__=='__main__':main()
