"""Record the assistant's actual 42-sheet coarse screen, not human QC or GT."""
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_model_training_data import read,jsonl,write
from pallet.cluster_targets import digest

ROOT=PROJECT/'outputs/pallet_mask_model_requests_v1'
# 1-based candidate indices on the inspected RAW/M2 contact sheets. These are
# visual issue hypotheses, not target human labels and not automatic QC results.
WITHHOLD={2:{12,17,22,30,33},4:{21},5:{31,39,40},7:{47},9:{7},12:{1,3,18,31,36,38,39,45,46,47,48,50},
    14:{19},15:{7},20:{21,24,27,42,44,53,55,62},21:{45}}
NOTES={2:'开口脚底和斜视边缘有偏差，孔口/外环语义须人工核对',4:'部分闭孔在模型输出中未保留；这里只交外轮廓草稿，未认证孔洞或选面正确',
    5:'斜视、堆叠与脚底容易混面；不把模型折线当成语义角点',7:'闭孔/开口与堆叠仍须人工判断',9:'低对比与黑白饱和图脚底易偏移',
    11:'前梁与斜撑边界须人工逐像素修订，不把后方支撑并入',12:'脚底、孔口、堆叠和闭孔/开口混淆较多，明显混面者暂不交付',
    14:'保留窄条/斜视真实模型外形，不因旧类别元数据整类排除；选面未知不补造',
    16:'窄梁边界与两端支撑须细修，像素锯齿不等同真实角点',17:'薄梁/脚底低对比，模型上下缘可能系统偏移',
    18:'低对比后缘与前梁须区分，细边线仍待人工修订',20:'开口/闭孔、梁脚及后方物体容易混淆',21:'薄梁与三腿形态混合，真实面和底缘仍待人工确认'}


def main():
    path=ROOT/'private/visual_decisions.json'
    if path.exists():raise ValueError('Do not overwrite recorded visual decisions')
    inv=read(ROOT/'private/coarse_contact_sheets/inventory.json');inputs=read(ROOT/'input_manifest.json')
    refs={k:dict(contact_sheet=p['path'],contact_sheet_sha256=p['sha256'],candidate_index=i)
        for p in inv['pages'] for k,i in zip(p['target_keys'],p['indices'])}
    counts=Counter();decisions={}
    for p in jsonl(ROOT/'private/predictions.jsonl'):
        key=p['target_key'];cls=p['class_id'];ref=refs.get(key)
        issue=bool(ref and ref['candidate_index'] in WITHHOLD.get(cls,set()))
        publish=bool(p['polygon'] and not issue and counts[cls]<inputs['remaining_to100'][str(cls)])
        if publish:counts[cls]+=1
        reason=p['polygonization']['reason'] or ('coarse_visual_wrong_layer_floor_or_opening_risk' if issue else
            'coarse_screen_machine_draft_requires_manual_edit' if publish else 'reserve_not_issued_after_class_gap_filled')
        decisions[key]=dict(publish_as_machine_draft=publish,reason=reason,coarse_crop_inspected=bool(ref),
            entire_native_image_individually_inspected=False,inspection_actor='AI_assistant_not_human_annotator',
            model_geometry_modified=False,human_QC_pass=False,quality_certified=False,
            note_zh=NOTES.get(cls,'梁缘、脚底及实际观察面仍需人工复核；该粗筛不是原生像素准确率验收'),**(ref or {}))
    write(path,dict(predictions_sha256=digest(ROOT/'private/predictions.jsonl'),contact_sheet_inventory_sha256=digest(ROOT/'private/coarse_contact_sheets/inventory.json'),
        sheets_actually_coarsely_viewed=42,scope='AI coarse paired crop inspection, no target human labels, no output geometry edits, not quality release',
        decisions=decisions,issued_counts=dict(counts),native_capacity_statistic='input capacity is a deterministic one-pass frame/hash-disjoint partition, NOT a per-class maximum'))
    print('Machine drafts selected:',sum(counts.values()),dict(counts))


if __name__=='__main__':main()
