"""Only fresh protected targets after2041 real saves; true v2 M2 inference."""
from collections import Counter,defaultdict
from contextlib import closing
import hashlib
import math
from pathlib import Path
import shutil
import time
import json

import cv2
import numpy as np
from PIL import Image,ImageDraw,ImageFont

from .cluster_targets import digest,protected_snapshot
from .mask_annotation_update_v2_data import ROOT as TRAINING,TOTAL,context
from .mask_model_training_data import PROJECT,read,jsonl,write,sha,require,letterbox,gpu_receipt
from .mask_model_worklist import FLAGS,polygonize
from .mask_class_keypoints import convert,VERSION,SETTINGS
from .mask_remaining_classes import confirmed,original_rectangle
from .mask_template_refined import QUARANTINE,readonly
from .mask_quality_recovery import POSE,GALLERY,fingerprint
from .mask_quota_saved_extension import file_inventory,load_formal_evidence
from .pose_review_geometry import raster_mask

ROOT=PROJECT/'outputs/pallet_mask_annotation_update_requests_v2'
SCHEMA='updated2041_M2_class_standard_keypoint_preannotation_v2'
NAMESPACE='model-annotation-update-remaining-v2'
DRAFT_PREFIX='mask-annotation-update-remaining-v2:'


def raw_sha(raw):return hashlib.sha256(raw.encode()).hexdigest() if raw else None


def protected_sources(rows,records):
    protected=set(QUARANTINE)|{r['target_key'] for r in records}
    protected.update(r['target_key'] for r in jsonl(PROJECT/'outputs/pallet_mask_remaining_round5_v1/proposals.jsonl'))
    with closing(readonly(POSE)) as db:
        current=dict(db.execute('SELECT target_key,payload FROM annotations'));history=defaultdict(list)
        for key,raw in db.execute('SELECT target_key,payload FROM events ORDER BY id'):history[key].append(json.loads(raw))
    for key in set(current)|set(history):
        values=history[key]+([json.loads(current[key])] if key in current else [])
        if key not in current or any(v.get('state') in ('deleted','deferred','confirmed') or confirmed(v) or not original_rectangle(v.get('polygon'),rows[key]) for v in values):protected.add(key)
    inventories={}
    for pattern in ('requests.jsonl','shortlist.jsonl','inspection_targets.jsonl'):
        for path in sorted((PROJECT/'outputs').rglob(pattern)):
            if path.is_relative_to(ROOT):continue
            inventories[str(path.relative_to(PROJECT))]=digest(path)
            protected.update(r['target_key'] for r in jsonl(path) if r.get('target_key') in rows)
    stores={}
    for path in sorted((PROJECT/'outputs').glob('pallet_mask*_reviews_v*/mask_reviews.sqlite3')):
        with closing(readonly(path)) as db:
            for table in ('reviews','events'):protected.update(k for k, in db.execute(f'SELECT DISTINCT target_key FROM {table}') if k in rows)
        stores[str(path.relative_to(PROJECT))]=fingerprint(path)
    return protected,current,inventories,stores


def stage():
    from scripts.verify_mask_under50_requests import native_quality
    require(not ROOT.exists(),'New immutable worklist required')
    manifest=read(TRAINING/'dataset_manifest.json');records=jsonl(TRAINING/'private/training_records.jsonl')
    require(len(records)==manifest['records']==2041,'Real completed145 +1896 sources required')
    formal,rows,evidence=load_formal_evidence(read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json'))
    counts=Counter(r['class_id'] for r in records);gaps={c:max(0,100-counts[c]) for c in range(1,23)}
    protected,current,inventories,stores=protected_sources(rows,records)
    frames={rows[k]['frame_id'] for k in protected};hashes={digest(formal/name) for name in {rows[k]['image'] for k in protected}}
    available={};reasons=Counter()
    for key,row in sorted(rows.items()):
        if not gaps[row['final_class_id']]:continue
        if key in protected or row['frame_id'] in frames:reasons['prior_protected_target_or_frame']+=1;continue
        try:quality=native_quality(row,evidence)
        except ValueError as error:reasons[str(error)]+=1;continue
        h=digest(formal/row['image'])
        if h in hashes:reasons['prior_protected_image_bytes']+=1;continue
        available[key]=(quality,h)
    capacity={}
    for cls in range(1,23):
        fs=set();hs=set()
        for key,(_,h) in sorted(available.items()):
            row=rows[key]
            if row['final_class_id']==cls and row['frame_id'] not in fs and h not in hs:fs.add(row['frame_id']);hs.add(h)
        capacity[cls]=len(fs)
    order=sorted((c for c in range(1,23) if gaps[c]),key=lambda c:(capacity[c],c))
    selected=[];groups=Counter();policies=Counter()
    for cls in order:
        for _ in range(4*gaps[cls]+16):
            options=[k for k,(_,h) in available.items() if rows[k]['final_class_id']==cls and rows[k]['frame_id'] not in frames and h not in hashes]
            if not options:break
            key=min(options,key=lambda k:(groups[cls,rows[k]['group_id']],policies[cls,rows[k]['policy_id']],
                -available[k][0]['bbox_height_native_pixels'],-available[k][0]['clarity_score'],k));row=rows[key]
            frames.add(row['frame_id']);hashes.add(available[key][1]);groups[cls,row['group_id']]+=1;policies[cls,row['policy_id']]+=1
            selected.append(dict(target_key=key,class_id=cls,source=row,request_order=len(selected)+1,native_quality=available[key][0],
                image_sha256=available[key][1],pose_payload_raw_sha256=raw_sha(current.get(key)),gallery_payload_raw_sha256=None))
    ROOT.mkdir(mode=0o700);(ROOT/'private').mkdir(mode=0o700)
    write(ROOT/'private/shortlist.jsonl',selected,lines=True);shutil.copyfile(TRAINING/'class_keypoint_standard.json',ROOT/'class_keypoint_standard.json')
    write(ROOT/'input_manifest.json',dict(schema='fresh_remaining_after_completed145_staging_v2',actual_manual_total=2041,real_saved_before=dict(counts),remaining_to100=gaps,
        native_capacity_per_class_before_crossclass_assignment=capacity,allocation_policy='scarcest eligible class first; balanced groups/policies; unchanged native gate',
        previously_protected_targets=len(protected),prior_worklist_inventories_sha256=inventories,existing_review_store_fingerprints=stores,
        original_frame_shortlist_rejected_completed_and_deferred_sources_not_reopened=True,pose_fingerprint=fingerprint(POSE),gallery_fingerprint=fingerprint(GALLERY),
        configuration_sha256=file_inventory(PROJECT/'configs'),formal_protected=protected_snapshot(formal),
        formal_manifest_sha256=read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json')['formal_manifest_sha256'],
        training_dataset_manifest_sha256=digest(TRAINING/'dataset_manifest.json'),class_standard_sha256=digest(ROOT/'class_keypoint_standard.json'),
        shortlist_sha256=digest(ROOT/'private/shortlist.jsonl'),staged_counts=dict(Counter(r['class_id'] for r in selected)),skip_reasons=dict(reasons),
        conversion_version=VERSION,conversion_settings=SETTINGS))
    print(dict(state='fresh_candidates_staged_real_v2_training_still_required',count=len(selected),capacity=capacity,classes=dict(Counter(r['class_id'] for r in selected)),remaining=gaps),flush=True)


def infer():
    import torch
    from rfdetr import RFDETRSegSmall
    from .mask_annotation_full_train import normalize
    from .mask_model_improvement import predicted_rle
    from .mask_model_improvement_adapter import mask_logits,native_logits,highest_class_query
    require(not (ROOT/'private/predictions.jsonl').exists(),'Never overwrite completed inference')
    training=read(TRAINING/'TRAINING_HANDOFF.json');inputs=read(ROOT/'input_manifest.json')
    require(training['state']=='verified_both_completed145_warm_updates_all2041_not_quality_release' and not training['errors']
        and inputs['training_dataset_manifest_sha256']==training['dataset_manifest_sha256'],'Actual2041 training and checkpoint verification required')
    checkpoint=TRAINING/'m2/final_ema.pt';h=digest(checkpoint);require(h==training['runs']['m2']['checkpoint_sha256'],'Updated2041 M2 pin differs')
    gpu=gpu_receipt('m2');torch.set_num_threads(4);cv2.setNumThreads(1);weights=torch.load(checkpoint,map_location='cpu',weights_only=True)
    wrapper=RFDETRSegSmall(num_classes=1,resolution=576,device='cuda:0',pretrain_weights=str(PROJECT/'outputs/pallet_mask_model_training_v1/generic_pretraining/rf-detr-seg-small.pt'),gradient_checkpointing=True,compile=False)
    model=wrapper.model.model;model.load_state_dict(weights['model'],strict=True);model.cuda().eval();del weights
    _,_,evidence=load_formal_evidence(read(PROJECT/'outputs/pallet_mask_remaining_round5_v1/manifest.json'))
    standard=read(ROOT/'class_keypoint_standard.json');predictions=[];started=time.monotonic()
    write(ROOT/'private/inference_start.json',dict(checkpoint_sha256=h,training_handoff_sha256=digest(TRAINING/'TRAINING_HANDOFF.json'),model_route='m2',gpu=gpu,
        network_input='original_image_pixels_only_fixed_original_box_context',threshold=.5,query='highest_classification_only_no_target_GT',class_K_postprocessing_only=True))
    with torch.inference_mode():
        for index,r in enumerate(jsonl(ROOT/'private/shortlist.jsonl'),1):
            row=r['source'];roi=context(row['bbox'],row['size']);x1,y1,x2,y2=roi;grey=evidence.image(row['frame_id'])[y1:y2,x1:x2]
            canvas,_,_,transform=letterbox(grey,None,(576,576));output=model(normalize(canvas)[None].cuda());query,confidence=highest_class_query(output)
            mask=native_logits(mask_logits(output)[0,query],transform).sigmoid().cpu().numpy()>=.5;box=row['bbox'];area=int(mask.sum());ratio=area/(box['width']*box['height']);reason=None
            if mask[0].any() or mask[-1].any() or mask[:,0].any() or mask[:,-1].any():reason='model_mask_touches_context_edge'
            left=max(0,math.floor(box['x']-x1));top=max(0,math.floor(box['y']-y1));right=min(mask.shape[1],math.ceil(box['x']+box['width']-x1));bottom=min(mask.shape[0],math.ceil(box['y']+box['height']-y1))
            overlap=float(mask[top:bottom,left:right].sum()/max(1,area))
            if not .05<=ratio<=1.25:reason=reason or 'implausible_mask_area_for_original_bbox'
            if overlap<.75:reason=reason or 'model_mask_not_localized_to_requested_target'
            dense,dense_info=polygonize(mask) if reason is None else (None,dict(reason=reason));k=standard['classes'][str(r['class_id'])]['standard_count']
            if dense:polygon,info=convert(mask,dense,k,box['height'],origin=(x1,y1),native_size=row['size'])
            else:polygon,info=None,dict(reason=dense_info['reason'])
            predictions.append(dict(target_key=r['target_key'],class_id=r['class_id'],roi=roi,raw_native_prediction_rle=predicted_rle(mask),
                raw_dense_polygon_local=dense,raw_polygonization=dense_info,polygon=polygon,conversion=info,standard_count=k,selected_query=query,
                class_confidence_not_quality_probability=confidence,raw_mask_area=area,mask_bbox_area_ratio=ratio,mask_fraction_inside_original_bbox=overlap,checkpoint_sha256=h,threshold=.5))
            if index%100==0:print('Completed145 new2041 M2 inferred',index,flush=True)
    write(ROOT/'private/predictions.jsonl',predictions,lines=True)
    complete=dict(state='actual2041_M2_fresh_inference_and_classK_conversion_not_quality_pass',targets=len(predictions),
        keypoint_candidates=sum(bool(p['polygon']) for p in predictions),by_class=dict(Counter(p['class_id'] for p in predictions if p['polygon'])),
        rejections=dict(Counter(p['conversion']['reason'] for p in predictions if not p['polygon'])),checkpoint_sha256=h,gpu=gpu,seconds=time.monotonic()-started)
    write(ROOT/'private/inference_complete.json',complete);print(complete,flush=True)


def contacts():
    out=ROOT/'private/contact_sheets';out.mkdir();records={r['target_key']:r for r in jsonl(ROOT/'private/shortlist.jsonl')}
    formal=Path(read(PROJECT/'configs/active_formal_dataset.json')['dataset']);predictions=jsonl(ROOT/'private/predictions.jsonl')
    font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',13);pages=[]
    for cls in range(1,23):
        candidates=[p for p in predictions if p['class_id']==cls and p['polygon']]
        for start in range(0,len(candidates),24):
            chunk=candidates[start:start+24];sheet=Image.new('RGB',(1760,math.ceil(len(chunk)/4)*155),'#111a24');draw=ImageDraw.Draw(sheet)
            for i,p in enumerate(chunk):
                row=records[p['target_key']]['source'];b=row['bbox'];l=max(0,math.floor(b['x']-8));t=max(0,math.floor(b['y']-12));rr=min(row['size'][0],math.ceil(b['x']+b['width']+8));bt=min(row['size'][1],math.ceil(b['y']+b['height']+12))
                raw=Image.open(formal/row['image']).convert('RGB').crop((l,t,rr,bt));overlay=raw.copy();d=ImageDraw.Draw(overlay);points=[(x-l,y-t) for x,y in p['polygon']]
                d.line(points+[points[0]],fill='#55d5ff',width=1)
                for x,y in points:d.ellipse((x-1,y-1,x+1,y+1),fill='#ffbe43')
                scale=min(216/raw.width,112/raw.height);size=(max(1,round(raw.width*scale)),max(1,round(raw.height*scale)));x=(i%4)*440;y=(i//4)*155
                for j,image in enumerate((raw,overlay)):sheet.paste(image.resize(size,Image.Resampling.NEAREST),(x+220*j,y+24))
                draw.text((x+3,y+2),f'C{cls} #{start+i+1} {p["target_key"][:10]} K{len(points)}',font=font,fill='white')
                draw.text((x+3,y+136),'RAW                 NEW2041 M2 CLASS-K (not GT)',font=font,fill='#c5e1f4')
            name=f'C{cls:02d}_{start//24+1:02d}.png';sheet.save(out/name)
            pages.append(dict(path=str((out/name).relative_to(PROJECT)),sha256=digest(out/name),class_id=cls,target_keys=[p['target_key'] for p in chunk],candidate_indices=list(range(start+1,start+len(chunk)+1))))
    write(out/'inventory.json',dict(predictions_sha256=digest(ROOT/'private/predictions.jsonl'),pages=pages,scope='AI coarse paired crops only, never human QC'));print('Contact sheets',len(pages),flush=True)


def build():
    from .mask_annotation_update_v2_review import editor_js,validate
    from scripts.build_mask_remaining_direct_requests import build_font
    from .mask_gallery import ASSETS
    require(not (ROOT/'manifest.json').exists(),'Never overwrite a published/sealed worklist')
    inputs=read(ROOT/'input_manifest.json');standard=read(ROOT/'class_keypoint_standard.json');standard_sha=digest(ROOT/'class_keypoint_standard.json')
    h=read(ROOT/'private/inference_complete.json')['checkpoint_sha256'];decisions=read(ROOT/'private/visual_decisions.json')
    require(decisions['predictions_sha256']==digest(ROOT/'private/predictions.jsonl'),'Coarse inspection binding differs')
    records={r['target_key']:r for r in jsonl(ROOT/'private/shortlist.jsonl')};counts=Counter();selected=[];withheld=[]
    for pred in jsonl(ROOT/'private/predictions.jsonl'):
        key=pred['target_key'];cls=pred['class_id'];r=records[key];decision=decisions['decisions'][key]
        if not pred['polygon'] or not decision['publish'] or counts[cls]>=inputs['remaining_to100'][str(cls)]:
            withheld.append(dict(target_key=key,class_id=cls,reason=pred['conversion']['reason'] or decision['reason']));continue
        proof=dict(model_family='RF-DETR-Seg Small',training_version=str(TRAINING.relative_to(PROJECT)),checkpoint='m2/final_ema.pt',checkpoint_sha256=h,
            training_dataset_manifest_sha256=inputs['training_dataset_manifest_sha256'],training_handoff_sha256=digest(TRAINING/'TRAINING_HANDOFF.json'),
            predictions_sha256=digest(ROOT/'private/predictions.jsonl'),native_mask_rle_sha256=sha(pred['raw_native_prediction_rle']),threshold=.5,
            query_selected_by='classification_only_no_target_GT',corner_conversion=pred['conversion'],visual_inspection=decision,
            human_saved=False,assistant_redrawn=False,quality_gate_passed=False)
        p=dict(schema=SCHEMA,origin='updated_M2_prediction',status='model_preannotated_pending_human_review',target_key=key,class_id=cls,
            source=r['source'],polygon=pred['polygon'],vertex_count=len(pred['polygon']),formal_manifest_sha256=inputs['formal_manifest_sha256'],
            model_source_image_sha256=r['image_sha256'],pose_payload_raw_sha256=r['pose_payload_raw_sha256'],gallery_payload_raw_sha256=None,
            class_keypoint_constraint=dict(class_id=cls,standard_count=standard['classes'][str(cls)]['standard_count'],standard_sha256=standard_sha,
                method='unique_class_saved_polygon_vertex_count_mode',physical_semantic_slots_confirmed=False,ordered_clockwise=True),
            model_provenance=proof,mask_semantics='new2041_M2_class_K_visible_fork_face_draft_requires_human_review_not_GT',**dict.fromkeys(FLAGS,False))
        validate(p,standard,standard_sha,h);selected.append(p);counts[cls]+=1
    require(selected,'No safe new drafts; do not manufacture a handoff')
    formal=Path(read(PROJECT/'configs/active_formal_dataset.json')['dataset'])
    for folder in ('images','cases','masks','labelme'):(ROOT/folder).mkdir()
    for p in selected:
        key=p['target_key'];row=p['source'];polygon=p['polygon'];k=len(polygon)
        shutil.copyfile(formal/row['image'],ROOT/'images'/f'{key}.png');image=Image.open(ROOT/'images'/f'{key}.png').convert('RGB')
        draw=ImageDraw.Draw(image);points=[tuple(v) for v in polygon];draw.line(points+[points[0]],fill='#55d5ff',width=1)
        box=row['bbox'];left=max(0,math.floor(box['x']-12));top=max(0,math.floor(box['y']-16))
        right=min(row['size'][0],math.ceil(box['x']+box['width']+12));bottom=min(row['size'][1],math.ceil(box['y']+box['height']+16))
        crop=image.crop((left,top,right,bottom)).resize(((right-left)*3,(bottom-top)*3),Image.Resampling.NEAREST);draw=ImageDraw.Draw(crop)
        for i,(x,y) in enumerate(polygon,1):
            xx=(x-left)*3;yy=(y-top)*3;draw.ellipse((xx-2,yy-2,xx+2,yy+2),fill='#ffbe43');draw.text((xx+3,yy-9),str(i),fill='white',stroke_width=1,stroke_fill='black')
        crop.save(ROOT/'cases'/f'{key}.png');Image.fromarray(raster_mask(polygon,*row['size']).astype(np.uint8)*255).save(ROOT/'masks'/f'{key}.png')
        flags=dict(model_preannotation=True,human_confirmed=False,ground_truth_eligible=False)
        shapes=[dict(label='pallet',shape_type='polygon',points=polygon,group_id=row['box_index'],flags=flags)]
        shapes.extend(dict(label=f'kp_{i:02d}',shape_type='point',points=[point],group_id=row['box_index'],flags=flags) for i,point in enumerate(polygon,1))
        write(ROOT/'labelme'/f'{key}.json',dict(version='5.0.0',imagePath=f'../images/{key}.png',imageData=None,imageWidth=row['size'][0],imageHeight=row['size'][1],
            flags=flags,shapes=shapes,keypoints_xy=polygon,num_keypoints=k,class_id=p['class_id'],class_keypoint_constraint=p['class_keypoint_constraint'],
            keypoint_order_semantics='clockwise geometric slots, physical semantic correspondence not confirmed',model_checkpoint_sha256=h,
            annotation_scope='single_target_pending_human_review_not_GT'))
    write(ROOT/'proposals.jsonl',selected,lines=True)
    write(ROOT/'requests.jsonl',[dict(target_key=p['target_key'],class_id=p['class_id'],keypoint_count=p['vertex_count'],status='new2041_model_draft_pending_real_human_review') for p in selected],lines=True)
    write(ROOT/'private/withheld.json',withheld)
    page='<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>145完成后 · 新2041模型关键点复核</title><style>@font-face{font-family:Review;src:url("report-font.otf")}*{box-sizing:border-box}body{font:16px/1.6 Review,sans-serif;background:#101720;color:#e7edf5;max-width:1100px;margin:auto;padding:12px}article{border:1px solid #536479;padding:12px;margin:18px 0}p,h2,td{overflow-wrap:anywhere}img{display:block;max-width:100%;height:auto}a{color:#80ceff}table{width:100%;border-collapse:collapse}td,th{padding:5px;border:1px solid #536479}@media(max-width:480px){h1{font-size:23px}body{padding:8px}}</style>'
    page+=f'<h1>145已完成 · 新2041模型关键点复核</h1><p>前145张均已真实保存，共166条追加修订；合并旧人工来源共2041张、246个有标签分量完成M1/M2固定10轮更新。使用这次新M2最终EMA生成本批{len(selected)}张不同新图。旧337张及145张入口、人工事件、机器预测和本机草稿不重绑、不改写。</p><p>初始机器点数沿用所属类别标准；人工微调仍可点击边增点、拖点、删点、撤销和历史恢复。失败不跳转、不清草稿；实际保存点数单独留痕，类别标准不变。</p><p>机器草稿未保存不计完成；不自动加入训练集、GT、传播种子或机器人指令。训练拟合与转换IoU不是独立准确率。没有安全新图或角点结构存疑则暂缓，不重开历史拒绝/隔离/shortlist图凑数。沿用原访问码。</p><p>筛选 <select id="request-filter"><option value="">全部</option>'+''.join(f'<option value="{c}">Class {c} · {standard["classes"][str(c)]["standard_count"]}点</option>' for c in range(1,23))+'</select></p><table><tr><th>类别</th><th>标准点数</th><th>已保存人工</th><th>本批草稿</th><th>全保存后仍缺</th></tr>'
    for cls in range(1,23):
        page+=f'<tr><td>Class {cls}</td><td>{standard["classes"][str(cls)]["standard_count"]}</td><td>{inputs["real_saved_before"][str(cls)]}</td><td>{counts[cls]}</td><td>{max(0,inputs["remaining_to100"][str(cls)]-counts[cls])}</td></tr>'
    page+='</table>'
    for p in selected:
        key=p['target_key'];page+=f'<article id="target-{key}" data-class="{p["class_id"]}"><h2>Class {p["class_id"]} · 初始标准{p["vertex_count"]}点 · 待人工复核</h2><img loading="lazy" src="cases/{key}.png" alt="新2041模型关键点草稿"><p>核对观察面、梁缘和底边；点数一致不代表角点准确，人工可增删点。</p><a href="images/{key}.png">原图</a> · <a href="labelme/{key}.json">关键点LabelMe</a> · <a href="masks/{key}.png">草稿掩膜</a></article>'
    page+='<script>const f=document.getElementById("request-filter");f.onchange=()=>document.querySelectorAll("article").forEach(a=>a.hidden=!!f.value&&a.dataset.class!==f.value);</script></html>'
    (ROOT/'report_zh.html').write_text(page);js=editor_js();(ROOT/'model-editor.js').write_text(js);build_font(ROOT,page+js+(ASSETS/'editor.html').read_text())
    assets={name:digest(ROOT/name) for name in ('report_zh.html','report-font.otf','FONT_LICENSE.txt','model-editor.js')}
    for p in selected:
        for folder,ext in [('images','png'),('cases','png'),('masks','png'),('labelme','json')]:
            name=f'{folder}/{p["target_key"]}.{ext}';assets[name]=digest(ROOT/name)
    write(ROOT/'manifest.json',dict(schema='completed145_updated2041_M2_remaining_keypoint_worklist_v2',source_namespace=NAMESPACE,request_count=len(selected),
        class_counts=dict(counts),actual_human_saved_before=inputs['real_saved_before'],base_manual_count=2041,target_per_class=100,filter_classes=list(range(1,23)),
        checkpoint_sha256=h,training_dataset_manifest_sha256=inputs['training_dataset_manifest_sha256'],training_handoff_sha256=digest(TRAINING/'TRAINING_HANDOFF.json'),
        class_standard_sha256=standard_sha,standard_counts={c:s['standard_count'] for c,s in standard['classes'].items()},input_manifest_sha256=digest(ROOT/'input_manifest.json'),
        proposals_sha256=digest(ROOT/'proposals.jsonl'),requests_sha256=digest(ROOT/'requests.jsonl'),predictions_sha256=digest(ROOT/'private/predictions.jsonl'),
        visual_decisions_sha256=digest(ROOT/'private/visual_decisions.json'),public_assets=assets,source_fingerprints=inputs['existing_review_store_fingerprints'],
        conditional_gap_after_all_drafts_saved={str(c):max(0,inputs['remaining_to100'][str(c)]-counts[c]) for c in range(1,23)},
        qualified_labels_created=0,agent_human_events_created=0,model_production_activated=False,quality_not_certified=True))
    print(dict(state='new2041_M2_fresh_classK_drafts_built_independent_verification_pending',count=len(selected),classes=dict(counts)),flush=True)
