"""Offline quality recovery: immutable evidence, descriptive replay and train-only CV.

This module never activates a gallery, writes a human store, changes a frozen
engine, trains a pose model, or declares a saved research polygon to be GT.
"""
from collections import Counter,defaultdict
from contextlib import closing
from dataclasses import asdict
from datetime import datetime,timezone
import hashlib
import html
import json
from pathlib import Path
import sqlite3

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

from .cluster_targets import digest,protected_snapshot
from .mask_quality_metrics import compare_polygons,summarize,stratified,release_decision
from . import mask_boundary_fit as fitter
from .mask_quota_saved_extension import file_inventory,load_formal_evidence
from .mask_template_refined import QUARANTINE,read_jsonl,snapshot_database,readonly
from .mask_quota_completion import publication_inventory
from .mask_saved_preannotations_v2 import prelabel_registry,combine_registries,resolve_event,registry_key,validate_gallery_event
from .mask_remaining_classes import validated_manual_source,original_rectangle
from .pose_review_geometry import canonical
from .mask_template_transfer import ImageEvidence
from .mask_template_continue import attempt_target as legacy_attempt

PROJECT=Path(__file__).resolve().parents[1]
PARENT=PROJECT/'outputs/pallet_mask_remaining_round5_v1'
POSE=PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'
GALLERY=PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3'
DEFAULT_OUTPUT=PROJECT/'outputs/pallet_mask_quality_recovery_v2'
PARENT_PINS={'manifest.json':'eced4c61119ee63bef7f80e4ae92d76db3d28f3228daef049fa00ad5da69e487',
    'verification.json':'5165170284205283adfaa6514c65cc8126773f49be54ed6398f1dba55f321631'}
PUBLICATIONS={3:'pallet_mask_template_bulk_v5',4:'pallet_mask_template_refined_v2',5:'pallet_mask_template_refined_v3',
    6:'pallet_mask_quota_completion_v2',7:'pallet_mask_quota_100_v2',8:'pallet_mask_quota_100_continue_v1',
    9:'pallet_mask_quota_100_complete_v1',10:'pallet_mask_remaining_expand_v1',11:'pallet_mask_remaining_continue_v1',
    12:'pallet_mask_remaining_round2_v1',13:'pallet_mask_remaining_round3_v1',14:'pallet_mask_remaining_round4_v1',15:'pallet_mask_remaining_round5_v1'}


def sha(value):return hashlib.sha256(canonical(value)).hexdigest()
def raw_sha(value):return hashlib.sha256(value.encode('utf-8')).hexdigest()
def read(path):return json.loads(Path(path).read_text())
def require(value,message):
    if not value:raise ValueError(message)


def write(path,value,jsonl=False):
    path=Path(path)
    with path.open('xb') as stream:stream.write(b''.join(canonical(v)+b'\n' for v in value) if jsonl else canonical(value)+b'\n')
    path.chmod(0o600)


def fingerprint(path):
    """Raw SQLite rows, schema and metadata; read-only and independent of WAL layout."""
    with closing(readonly(path)) as db:
        db.execute('PRAGMA query_only=ON');db.execute('BEGIN')
        schema=list(db.execute('SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name'))
        tables={r[1]:sha(sorted(canonical(list(row)).decode() for row in db.execute('SELECT * FROM "'+r[1]+'"')))
            for r in schema if r[0]=='table' and r[1].replace('_','').isalnum()}
    return dict(schema_sha256=sha(schema),tables=tables)


def settings():
    return dict(version='mask_quality_recovery_research_v1',algorithm=fitter.VERSION,numerical_settings=asdict(fitter.SETTINGS),
        execution_domain='formal_train_only',evaluation='deterministic_connected_group_3fold_out_of_fold',
        near_duplicate=dict(dhash_bits=128,hamming_max=2,normalized_patch_ncc_min=.995,same_class_and_policy_required=True),
        ambiguous_surface_classes=[14],unknown_view_is_not_compatible=True,
        retrieval_uses_only_native_image_class_bbox_sensor_policy_and_known_view=True,
        original_engines_modified=False,original_propagation_qualification_unchanged=True,
        experimental_four_point_boundary_fit_is_not_old_template_authorization=True,
        quality_gate=dict(minimum_accepted=10,iou_median_min=.95,fraction_iou_at_least_09_min=.9,
            boundary_max='HD95 <= max(2 native pixels, .10 * target bbox height)'),
        reference_polygons_are_saved_research_annotations_not_GT=True,automatic_publication=False,
        validation_or_test_labels_used_by_new_algorithm=False,pose_model_training=False)


def load_catalog(out):
    m=read(PARENT/'manifest.json')
    require(all(digest(PARENT/n)==h for n,h in PARENT_PINS.items()),'Parent independent evidence changed')
    require(all(digest(PROJECT/n)==h for n,h in m['frozen_code_sha256'].items()),'Frozen algorithm changed')
    formal,rows,evidence=load_formal_evidence(m);formal_sha=m['formal_manifest_sha256']
    require(len(rows)==12344,'Fixed target denominator changed')
    paths={v:PROJECT/'outputs'/n for v,n in PUBLICATIONS.items()};publications=publication_inventory(paths,formal_sha)
    pose_path=out/'private/pose_snapshot.sqlite3';gallery_path=out/'private/gallery_snapshot.sqlite3'
    snapshot_database(POSE,pose_path);snapshot_database(GALLERY,gallery_path)
    with closing(readonly(pose_path,True)) as db:
        binding=json.loads(db.execute("SELECT value FROM metadata WHERE key='binding'").fetchone()[0])
        require(binding['formal_manifest_sha256']==formal_sha,'Foreign pose database')
        current={k:json.loads(raw) for k,raw in db.execute('SELECT target_key,payload FROM annotations')}
        event_keys={k for k, in db.execute('SELECT DISTINCT target_key FROM events')};pose_events=db.execute('SELECT COUNT(*) FROM events').fetchone()[0]
        pose_records=[]
        for old in read_jsonl(PARENT/'all_manual_sources.jsonl'):
            key=old['target_key'];v,_,record=validated_manual_source(db,key,rows[key],digest(pose_path),sha(binding))
            require(record['current_payload_raw']==old['current_payload_raw'],'Protected original pose source changed')
            pose_records.append(dict(target_key=key,row=rows[key],polygon=v['polygon'],origin='saved_pose',revision=v['revision'],
                payload_sha256=sha(v),event_raw_sha256=record['human_event_sha256'],initial_polygon=None,batch='pose_manual_no_machine_pair'))
    registries=[];inputs={}
    for n,version in ((1,13),(2,14),(3,15)):
        directory=PROJECT/f'outputs/pallet_mask_preannotated_requests_v{n}'
        registries.append(prelabel_registry(directory,rows,formal_sha,publications[version],current,event_keys,version,f'v{n}'))
        inputs[str(directory.relative_to(PROJECT))]=dict(manifest=digest(directory/'manifest.json'),verification=digest(directory/'verification.json'),
            proposals=digest(directory/'proposals.jsonl'))
    registry=combine_registries(*registries);cache={};histories=defaultdict(list);event_audit=[]
    with closing(readonly(gallery_path,True)) as db:
        require(dict(db.execute('SELECT key,value FROM metadata')).get('formal_manifest_sha256')==formal_sha,'Foreign gallery database')
        for event_id,key,revision,raw in db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'):
            value=json.loads(raw);reference=resolve_event(value,rows,formal_sha,publications,registry,cache)
            validate_gallery_event(value,rows[key],reference,revision)
            require(value['proposal_polygon']==reference['proposal']['polygon'],'Recorded initial polygon differs from actual proposal')
            histories[key].append((event_id,revision,raw,value,reference))
            event_audit.append(dict(event_id=event_id,target_key=key,revision=revision,payload_raw_sha256=raw_sha(raw),
                publication=value['proposal_publication'],base_proposal_sha256=value['base_proposal_id'],source_registry=reference['kind']))
        gallery_records=[]
        for key,revision,raw in db.execute('SELECT target_key,revision,payload FROM reviews ORDER BY target_key'):
            history=histories[key]
            require(history and history[-1][1:3]==(revision,raw) and len({h[1] for h in history})==len(history),'Not exact raw unique latest event')
            require(key not in QUARANTINE and key not in {r['target_key'] for r in pose_records},'Quarantined or duplicated source')
            value=json.loads(raw);first=history[0];reference=first[4]
            require(not original_rectangle(value['polygon'],rows[key]),'Original rectangle cannot become a contour reference')
            gallery_records.append(dict(target_key=key,row=rows[key],polygon=value['polygon'],origin='saved_gallery',revision=revision,
                payload_sha256=sha(value),event_raw_sha256=raw_sha(raw),initial_polygon=first[3]['proposal_polygon'],
                batch='prelabel_'+reference['namespace'] if reference['kind']=='independent_preannotation' else 'historical_gallery',
                initial_publication=first[3]['proposal_publication'],history_revisions=len(history)))
    catalog=pose_records+gallery_records
    require(len({r['target_key'] for r in catalog})==len(catalog),'Duplicate actual source')
    write(out/'private/event_binding_audit.jsonl',event_audit,True);write(out/'private/source_catalog.jsonl',catalog,True)
    source_summary=dict(pose_contours=len(pose_records),gallery_contours=len(gallery_records),total_contours=len(catalog),
        pose_store_saved=len(current),pose_store_events=pose_events,gallery_events=len(event_audit),
        all_raw_event_source_bindings_verified=True,old_review_only_rectangles=5,pending_original_rectangles=2,
        rectangle_and_conversation_records_not_contour_references=True,task_inputs=inputs,
        publication_inputs={str(v):dict(manifest_sha256=p['manifest_sha256'],proposals_sha256=p['proposals_sha256'],verification_sha256=p['verification_sha256']) for v,p in publications.items()})
    return catalog,source_summary,formal,rows,evidence


def descriptive_replay(catalog):
    records=[]
    for r in catalog:
        if r['initial_polygon'] is None:continue
        row=r['row'];metrics=compare_polygons(r['initial_polygon'],r['polygon'],row['size'],row['bbox']['height'])
        records.append(dict(target_key=r['target_key'],class_id=row['final_class_id'],batch=r['batch'],split=row['split'],
            bbox_height=row['bbox']['height'],reference_revision=r['revision'],**metrics))
    return records,dict(all=summarize(records),by_batch=stratified(records,'batch'),by_class=stratified(records,'class_id'),
        by_split=stratified(records,'split'),comparison_is_annotation_revision_agreement_not_accuracy=True,
        historical_val_test_descriptive_only_no_model_selection=True)


def dhash(image,box):
    x,y,w,h=(box[k] for k in ('x','y','width','height'));a=image[max(0,int(y)):min(image.shape[0],int(np.ceil(y+h))),max(0,int(x)):min(image.shape[1],int(np.ceil(x+w)))]
    if not a.size:raise ValueError('Empty reference image crop')
    a=cv2.resize(a,(17,8),interpolation=cv2.INTER_AREA)
    return int.from_bytes(np.packbits(a[:,1:]>a[:,:-1]).tobytes(),'big')


def independent_components(catalog,evidence):
    """Union groups / frames / exact image-PCD / verified near duplicates, before folds."""
    parent=list(range(len(catalog)));links=[]
    def find(i):
        while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
        return i
    def union(a,b,reason):
        aa,bb=find(a),find(b)
        if aa!=bb:parent[max(aa,bb)]=min(aa,bb);links.append(dict(left=catalog[a]['target_key'],right=catalog[b]['target_key'],reason=reason))
    seen={};hashes={};buckets=defaultdict(list)
    for i,r in enumerate(catalog):
        row=r['row'];image=evidence.image(row['frame_id']);hashes[i]=dhash(image,row['bbox'])
        for kind,value in (('group',row['group_id']),('frame',row['frame_id']),('pcd',row['source_pcd_sha256']),('image',sha(dict(size=image.shape,bytes_sha256=hashlib.sha256(image.tobytes()).hexdigest())))):
            token=(kind,value)
            if token in seen:union(i,seen[token],kind)
            else:seen[token]=i
        bucket=(row['final_class_id'],row['policy_id'])
        for j in buckets[bucket]:
            if find(i)==find(j) or (hashes[i]^hashes[j]).bit_count()>2:continue
            a,b=evidence.patch(row['target_key']),evidence.patch(catalog[j]['target_key'])
            if fitter.correlate(a,b)>=.995:union(i,j,'native_crop_near_duplicate_dhash_and_ncc')
        buckets[bucket].append(i)
    groups=defaultdict(list)
    for i,r in enumerate(catalog):groups[find(i)].append(r['target_key'])
    components={key:sha(sorted(keys)) for keys in groups.values() for key in keys}
    return components,links


def fold_for(component,folds=3):return int(component[:16],16)%folds


def eligible_reference(target,source,components,folds=3):
    a,b=target['row'],source['row']
    if a['split']!='train' or b['split']!='train':return False
    if components[target['target_key']]==components[source['target_key']]:return False
    if fold_for(components[target['target_key']],folds)==fold_for(components[source['target_key']],folds):return False
    if any(a[f]!=b[f] for f in ('final_class_id','policy_id','viewpoint_candidate')):return False
    if a.get('viewpoint_candidate') in (None,'unknown') or a['final_class_id']==14:return False
    return True


def visible_input(record,evidence):
    row=record['row']
    return dict(image=evidence.image(row['frame_id']),box=row['bbox'],class_id=row['final_class_id'],policy_id=row['policy_id'],known_view=row.get('viewpoint_candidate'))


def predict(target_input,references,settings=fitter.SETTINGS):
    """No target polygon, pose, identity or group information can enter here."""
    require(set(target_input)=={'image','box','class_id','policy_id','known_view'},'Unapproved target input')
    target=target_input['image'];box=target_input['box'];ranked=[]
    for reference in references:
        rank=fitter.correlate(fitter.patch(reference['image'],reference['box']),fitter.patch(target,box))
        ranked.append((rank,reference))
    ranked.sort(key=lambda v:(-v[0],v[1]['reference_key']))
    candidates=[];attempts=[];used_components=set()
    for _,r in ranked:
        if r['independent_component'] in used_components:continue
        used_components.add(r['independent_component'])
        if len(used_components)>settings.maximum_references:break
        initial,alignment=fitter.coarse_alignment(r['image'],target,r['box'],box,r['polygon'],settings)
        trial=dict(reference_key=r['reference_key'],reference_payload_sha256=r['payload_sha256'],independent_component=r['independent_component'],alignment=alignment)
        if initial is not None:
            candidate,diagnostic=fitter.refine_polygon(r['image'],target,r['polygon'],initial,box,settings)
            trial['native_fit']=diagnostic
            if candidate is not None:candidates.append(dict(reference_key=r['reference_key'],independent_component=r['independent_component'],
                polygon=candidate,family=fitter.shape_family(r['polygon'],r['box'])))
        attempts.append(trial)
    chosen,consensus=fitter.consensus(candidates,settings)
    if not references:consensus=dict(rejection='no_compatible_independent_reference')
    return None if chosen is None else chosen['polygon'],dict(attempts=attempts,consensus=consensus,
        rejection=consensus['rejection'],candidate_family=None if chosen is None else chosen['family'])


def evaluate_train(catalog,components,evidence):
    train=[r for r in catalog if r['row']['split']=='train'];predictions=[];scores=[];baseline_predictions=[];baseline_scores=[]
    for number,target in enumerate(train,1):
        sources=[r for r in train if eligible_reference(target,r,components)]
        # The selector sees source geometry but never target annotation geometry.
        refs=[dict(reference_key=r['target_key'],image=evidence.image(r['row']['frame_id']),box=r['row']['bbox'],polygon=r['polygon'],
            payload_sha256=r['payload_sha256'],independent_component=components[r['target_key']]) for r in sources]
        polygon,diagnostic=predict(visible_input(target,evidence),refs)
        row=target['row'];item=dict(target_key=target['target_key'],class_id=row['final_class_id'],split='train',
            fold=fold_for(components[target['target_key']]),component=components[target['target_key']],compatible_source_count=len(sources),
            polygon=polygon,status='offline_candidate_pending_quality_evaluation' if polygon else 'abstained',diagnostics=diagnostic,
            production_saved=False,human_confirmed=False,automatic_training_eligible=False,robot_command_eligible=False)
        if polygon is not None:
            metric=compare_polygons(polygon,target['polygon'],row['size'],row['bbox']['height'])
            metric.update(target_key=target['target_key'],class_id=row['final_class_id'],bbox_height=row['bbox']['height'],fold=item['fold'])
            scores.append(metric)
        predictions.append(item)
        ranked=sorted(((fitter.correlate(evidence.patch(r['target_key']),evidence.patch(target['target_key'])),r)
            for r in sources if len(r['polygon'])>4),key=lambda v:(-v[0],v[1]['target_key']))
        independent=set();legacy_sources={}
        for _,r in ranked:
            component=components[r['target_key']]
            if component in independent:continue
            independent.add(component);legacy_sources[r['target_key']]=dict(row=r['row'],polygon=r['polygon'])
            if len(independent)>=fitter.SETTINGS.maximum_references:break
        accepted,trials,outcome=legacy_attempt(target['target_key'],row,legacy_sources,evidence)
        baseline_predictions.append(dict(target_key=target['target_key'],class_id=row['final_class_id'],split='train',fold=item['fold'],component=item['component'],
            status='offline_legacy_candidate' if accepted else 'abstained',polygon=accepted['polygon'] if accepted else None,
            eligible_reference_keys=list(legacy_sources),attempts=trials,rejection=None if accepted else outcome['reason'],
            method='frozen_original_with_explicit_three_independent_reference_budget_not_historical_full_scan'))
        if accepted:
            metric=compare_polygons(accepted['polygon'],target['polygon'],row['size'],row['bbox']['height'])
            baseline_scores.append(dict(target_key=target['target_key'],class_id=row['final_class_id'],bbox_height=row['bbox']['height'],fold=item['fold'],**metric))
        if number%100==0:print(json.dumps(dict(stage='train_only_group_cv',completed=number,total=len(train),candidates=len(scores))),flush=True)
    return predictions,scores,baseline_predictions,baseline_scores


def render_report(out,descriptive,records,predictions,scores,decision,source_summary,baseline):
    tables=[]
    for label,stats in descriptive['by_batch'].items():
        tables.append('<tr><td>'+html.escape(label)+'</td>'+''.join(f'<td>{stats[f]:.3f}</td>' if stats[f] is not None else '<td>—</td>'
            for f in ('count','iou_median','hd95_native_pixels_median','polygon_changed'))+'</tr>')
    details=Counter(p['diagnostics']['rejection'] or 'accepted' for p in predictions)
    page='''<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>掩膜质量恢复：离线回放</title>
<style>body{font:16px/1.6 sans-serif;max-width:1100px;margin:auto;padding:20px}table{border-collapse:collapse}td,th{border:1px solid #999;padding:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}img{max-width:100%}*{box-sizing:border-box}</style>
<h1>掩膜质量恢复：只读证据与离线验证</h1><p>人工保存轮廓是研究参考，不自动成为GT。历史val/test只用于修订差异的描述统计；新算法只在正式train内进行连通采集组隔离交叉验证，不读取目标标注做候选生成或选择，不自动发布。</p>'''
    page+=f'<p>真实轮廓来源 {source_summary["total_contours"]}；可回放初稿/修订对 {len(records)}。位姿载荷、选面、标尺、访问码不进入算法或报告。</p>'
    page+='<h2>历史初稿与最新人工修订的差异（不是正确率）</h2><table><tr><th>批次</th><th>数量</th><th>IoU中位数</th><th>HD95像素中位数</th><th>修改数</th></tr>'+''.join(tables)+'</table>'
    page+='<h2>新方法：兼容人工参考＋原生边界线拟合＋多参考一致性</h2><p>不再由助手填写目标坐标。仿射只作初始化；逐边检测有方向的灰度跳变，稳健拟合直线，以相邻线交点形成原拓扑轮廓。弱边、歧义、未知视面、Class14未精分长短面、参考不足或独立参考不一致均拒绝。四点只进入独立实验拟合，不改变旧严格传播模板资格。</p>'
    page+='<p>采集组、同帧、同原图/PCD和明确近重复连成同一隔离分量；同一分量不得跨参考与目标。按分量三折，只有其它折且同类/同策略/明确相同候选视面来源可用；身份和组别仅用于排除泄漏，不是数值模型输入。粗粒度视面仍不能证明物理兼容，不能据此授权生产。</p>'
    page+='<h2>预先声明的质量门禁</h2><pre>'+html.escape(json.dumps(decision,ensure_ascii=False,indent=2))+'</pre>'
    page+='<h2>同样隔离规则下的冻结旧算法基线</h2><p>旧算法只用超过四点的来源，最多三个独立分量的兼容参考；该受控基线不是旧版本全量扫描结果。看图初稿只有已有1002对可回放，不为新算法生成目标专用手写坐标。</p><pre>'+html.escape(json.dumps(baseline,ensure_ascii=False,indent=2))+'</pre>'
    page+='<h2>拒绝分布和交付率</h2><pre>'+html.escape(json.dumps(dict(rejections=dict(details),train_targets=len(predictions),accepted=len(scores)),ensure_ascii=False,indent=2))+'</pre>'
    page+='<p>门禁失败或样本不足时不发新批次，不用零交付虚构高精度。没有恢复神经网络训练，没有改在线配置、原始标签、正式划分、旧交付或人工历史。后续应按失败类型补足实际观察面标识和独立组人工来源，再验证小批10–15张。</p></html>'
    (out/'report_zh.html').write_text(page)


def run(out=DEFAULT_OUTPUT):
    out=Path(out).resolve();require(out.parent==PROJECT/'outputs' and not out.exists(),'Use a fresh outputs directory; preserve existing evidence')
    cv2.setNumThreads(1);before={name:fingerprint(path) for name,path in (('pose',POSE),('gallery',GALLERY))};configs=file_inventory(PROJECT/'configs')
    code={name:digest(PROJECT/name) for name in ('pallet/mask_quality_recovery.py','pallet/mask_quality_metrics.py','pallet/mask_boundary_fit.py')}
    out.mkdir(mode=0o700);(out/'private').mkdir(mode=0o700);write(out/'settings.json',settings())
    catalog,source_summary,formal,rows,evidence=load_catalog(out)
    protected=protected_snapshot(formal);require(len(protected)==20768 and protected==read(PARENT/'protected_formal_after.json'),'Formal file protection changed')
    write(out/'private/protected_formal_before.json',protected)
    records,descriptive=descriptive_replay(catalog);write(out/'descriptive_records.jsonl',records,True);write(out/'descriptive_summary.json',descriptive)
    components,links=independent_components(catalog,evidence)
    write(out/'private/leakage_components.json',dict(by_target=components,links=links))
    predictions,scores,baseline_predictions,baseline_scores=evaluate_train(catalog,components,evidence)
    write(out/'offline_predictions.jsonl',predictions,True);write(out/'train_oof_metrics.jsonl',scores,True)
    write(out/'legacy_predictions.jsonl',baseline_predictions,True);write(out/'legacy_train_oof_metrics.jsonl',baseline_scores,True)
    decision=release_decision(scores,len(predictions))
    baseline=dict(method='frozen_original_three_independent_reference_budget',count=len(baseline_predictions),accepted=len(baseline_scores),
        delivery_rate=len(baseline_scores)/len(baseline_predictions) if baseline_predictions else 0.,quality=summarize(baseline_scores),
        rejections=dict(Counter(p['rejection'] or 'accepted' for p in baseline_predictions)))
    render_report(out,descriptive,records,predictions,scores,decision,source_summary,baseline)
    require(configs==file_inventory(PROJECT/'configs') and before=={name:fingerprint(path) for name,path in (('pose',POSE),('gallery',GALLERY))},'Live sources/configuration changed during audit')
    require(protected_snapshot(formal)==protected,'Formal files changed during evaluation')
    require(all(digest(PROJECT/name)==h for name,h in code.items()),'New algorithm code changed during evaluation')
    result=dict(state='completed_offline_not_published',source_summary=source_summary,descriptive_summary=descriptive,
        train_oof_targets=len(predictions),train_oof_candidates=len(scores),rejections=dict(Counter(p['diagnostics']['rejection'] or 'accepted' for p in predictions)),
        independent_components=len(set(components.values())),train_metrics=summarize(scores),by_class=stratified(scores,'class_id'),release_gate=decision,
        baseline=baseline,by_class_delivery={str(c):dict(total=sum(p['class_id']==c for p in predictions),accepted=sum(s['class_id']==c for s in scores))
            for c in sorted({p['class_id'] for p in predictions})},
        compatible_reference_targets=sum(p['compatible_source_count']>0 for p in predictions),
        attempted_source_pairs=sum(len(p['diagnostics']['attempts']) for p in predictions),
        pair_rejections=dict(Counter((a.get('native_fit') or a['alignment'])['rejection'] or 'fitted'
            for p in predictions for a in p['diagnostics']['attempts'])),
        settings_sha256=digest(out/'settings.json'),code_sha256=code,configuration_sha256=configs,source_fingerprints=before,
        protected_formal_files=20768,fixed_denominator=12344,all_protected_sources_unchanged=True,
        output_artifacts=file_inventory(out),production_annotation_writes=0,configuration_writes=0,service_writes=0,
        neural_network_training=False,automatic_publication=False,completed_at=datetime.now(timezone.utc).isoformat())
    write(out/'result.json',result);print(json.dumps({k:v for k,v in result.items() if k in ('state','train_oof_targets','train_oof_candidates','rejections','release_gate')}),flush=True)
    return result


if __name__=='__main__':
    import argparse
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path,default=DEFAULT_OUTPUT);args=parser.parse_args();run(args.output)
