"""Read-only, class-stratified audit of human drafts, not a GT generator.

Visible point statistics, support hypotheses, physical face bounds, and labels
are deliberately distinct. No online store/application is instantiated here.
"""
from __future__ import annotations

import argparse
import base64
from collections import Counter,defaultdict
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
import copy
import csv
from datetime import datetime,timezone
import hashlib
from html import escape
import io
import json
import math
import os
from pathlib import Path
import shutil
import sqlite3
from zipfile import ZipFile,ZIP_DEFLATED

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

from .cluster_targets import digest,load_dataset,protected_snapshot,target_key
from .data.orientation import orient_grid
from .data.pcd import read_pcd
from .fork_geometry import valid_xyz
from .pose_review_axes import AxesPolicy
from .pose_review_units import MetrePolicy
from .pose_review_geometry import GeometryEngine,basis_for,canonical,pose_value,retained

PROJECT=Path(__file__).resolve().parents[1]
LIVE=PROJECT/'outputs/pallet_pose_human_review_v1'
DEFAULT=PROJECT/'outputs/pallet_pose_annotation_audit_v1'
CLASSES=PROJECT/'outputs/pallet_appearance_center_reclassification_v1/targets.jsonl'
AUTO_EVENTS={'unit_normalization','axes_normalization'}
FONT=Path('/tmp/opencode/pallet_pose_design/NotoSansCJKsc-Regular.otf')


def now():return datetime.now(timezone.utc).isoformat(timespec='seconds')


def write_json(path,value):
    path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
    tmp=path.with_suffix(path.suffix+'.tmp');tmp.write_bytes(canonical(value));tmp.replace(path)


def rows(path):return [json.loads(s) for s in Path(path).read_text().splitlines() if s.strip()]


def write_rows(path,values):Path(path).write_bytes(b''.join(canonical(v)+b'\n' for v in values))


def read_snapshot(out):
    with closing(sqlite3.connect((out/'snapshot/reviews.sqlite3').resolve().as_uri()+'?mode=ro&immutable=1',uri=True)) as db:
        current={k:json.loads(raw) for k,raw in db.execute('SELECT target_key,payload FROM annotations')}
        histories=defaultdict(list)
        for key,revision,raw in db.execute('SELECT target_key,revision,payload FROM events ORDER BY id'):
            histories[key].append(json.loads(raw))
    return current,histories


def freeze(out):
    if out.exists() and any(out.iterdir()):raise ValueError('Choose a new, empty audit output; never overwrite previous evidence')
    out.mkdir(parents=True,exist_ok=True);snap=out/'snapshot';snap.mkdir()
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset']).resolve()
    binding=json.loads((LIVE/'protected_formal_snapshot.json').read_text())
    assert protected_snapshot(formal)==binding
    with closing(sqlite3.connect((LIVE/'annotations.sqlite3').resolve().as_uri()+'?mode=ro',uri=True)) as src,closing(sqlite3.connect(snap/'reviews.sqlite3')) as dest:
        src.backup(dest);dest.execute('PRAGMA journal_mode=DELETE')
        assert dest.execute('PRAGMA quick_check').fetchone()[0]=='ok'
    os.chmod(snap/'reviews.sqlite3',0o400)
    write_json(snap/'protected_formal.json',binding)
    shutil.copyfile(CLASSES,snap/'classes.jsonl')
    protected={}
    for name in ('configs/active_formal_dataset.json','configs/pallet_pose_review_units_v1.json','configs/pallet_pose_review_axes_v1.json',
                 'configs/active_pose_refinement.json','configs/active_pose_annotations.json',
                 'outputs/pallet_pose_benchmark_v4/pallet_pose_models_v4.zip','outputs/pallet_pose_benchmark_v4/pallet_pose_annotations_v4.zip'):
        protected[name]=digest(PROJECT/name)
    for name in ('pallet/pose_review_geometry.py','pallet/pose_review_units.py','pallet/pose_review_axes.py'):
        protected[name]=digest(PROJECT/name)
    current,histories=read_snapshot(out)
    write_rows(snap/'current_reviews.jsonl',current.values())
    write_json(snap/'manifest.json',dict(created_at=now(),formal=str(formal),formal_manifest_sha256=digest(formal/'manifest.json'),
        snapshot_db_sha256=digest(snap/'reviews.sqlite3'),class_source_sha256=digest(CLASSES),
        saved_targets=len(current),events=sum(map(len,histories.values())),protected_inputs=protected,
        source_DB_open_mode='read_only_SQLite_backup_API',source_annotation_writes=0,
        purpose='nonblind_annotation_quality_audit_not_training_or_confirmed_GT'))


def world_ruler(ruler):
    b=np.asarray(ruler['basis'],float);o=np.asarray(ruler['origin'],float)
    a=np.deg2rad(ruler['angle']);center=o+ruler['w']*b[:,0]+ruler['d']*b[:,1]
    width=np.cos(a)*b[:,0]+np.sin(a)*b[:,1];depth=-np.sin(a)*b[:,0]+np.cos(a)*b[:,1]
    return center,np.column_stack((width,depth,b[:,2]))


def comparable(r,sensor):return all(r['sensor'][k]==sensor[k] for k in ('forward_axis','forward_sign','up_axis','up_sign'))


def history_evidence(value,history):
    c,b=world_ruler(value['ruler']);scale=value['sensor']['scale_to_m']
    humans=[v for v in history if v.get('event_kind') not in AUTO_EVENTS and v.get('ruler') and v.get('state')!='deleted' and comparable(v,value['sensor'])]
    previous=None;changed=0;last=None
    for v in humans:
        vc,vb=world_ruler(v['ruler']);ratio=(scale if scale is not None else 1)/(v['sensor']['scale_to_m'] or 1)
        vc*=ratio;vw=v['ruler']['half_width']*2*ratio
        if last is not None:
            distance=float(np.linalg.norm((vc-last[0])@b[:,:2]));angle=float(np.rad2deg(np.arccos(np.clip(vb[:,1]@last[1],-1,1))))
            if distance>.0005 or angle>.05 or abs(vw-last[2])>.0005:changed+=1
        last=(vc,vb[:,1],vw)
    for v in reversed(humans):
        if v['revision']<value['revision']:
            pc,pb=world_ruler(v['ruler']);ratio=(scale if scale is not None else 1)/(v['sensor']['scale_to_m'] or 1)
            previous=dict(revision=v['revision'],center_source=(pc*ratio).tolist(),width_m=v['ruler']['half_width']*2*ratio,
                direction_source=(pb[:,1]*v['ruler'].get('direction_sign',1)).tolist());break
    first=humans[0] if humans else None
    first_delta=None
    if first:
        fc,_=world_ruler(first['ruler']);ratio=(scale if scale is not None else 1)/(first['sensor']['scale_to_m'] or 1)
        first_delta=((c-fc*ratio)@b).tolist()
    return dict(human_save_events=len(humans),geometric_revision_transitions=changed,
        multiple_human_saves_with_geometric_change=changed>0,previous=previous,first_to_current_local_m=first_delta,
        caution='保存/多次修订不自动等于人工确认；自动单位/轴向修订不计人工修正')


def support_hypothesis(local):
    """Diagnostic lower-band components only, NEVER confirmed physical legs."""
    if len(local)<40:return dict(status='insufficient_points',components=[])
    lo,hi=np.quantile(local[:,0],[.01,.99]);width=hi-lo
    if width<=1e-8:return dict(status='degenerate',components=[])
    hlo,hhi=np.quantile(local[:,2],[.03,.50]);band=local[(local[:,2]>=hlo)&(local[:,2]<=hhi)]
    hist,edges=np.histogram(band[:,0],bins=60,range=(lo,hi));smooth=np.convolve(hist,[.25,.5,.25],mode='same')
    on=smooth>=max(2.,smooth.max()*.22);components=[];start=None
    for i,v in enumerate(np.r_[on,False]):
        if v and start is None:start=i
        if not v and start is not None:
            if i-start>=2:components.append(dict(left=float(edges[start]),right=float(edges[i]),count=int(hist[start:i].sum())))
            start=None
    mid=None
    if len(components)==3:
        component=components[1];mid=(component['left']+component['right'])/2
    return dict(status='automatic_lower_band_components_not_confirmed_legs',components=components,
        possible_middle_component_center_m=mid,band_height_m=[float(hlo),float(hhi)])


def load_geometry(value,cache):
    token=value['geometry_token']
    if len(token)!=64 or any(c not in '0123456789abcdef' for c in token):raise ValueError('Invalid geometry token')
    meta=json.loads((cache/(token+'.json')).read_text())
    if meta['target_key']!=value['target_key'] or meta['polygon']!=value['polygon'] or meta['sensor']!=value['sensor']:
        raise ValueError('geometry_revision_sensor_or_polygon_mismatch')
    if digest(cache/(token+'.npz'))!=meta['full_resolution_artifact_sha256']:raise ValueError('geometry_hash_mismatch')
    with np.load(cache/(token+'.npz'),allow_pickle=False) as z:data={k:z[k].copy() for k in z.files}
    if len(np.unique(data['source_indices']))!=len(data['source_indices']):raise ValueError('duplicate_source_indices')
    selected=value['selected_faces']
    mask=(np.ones(len(data['xyz']),bool) if 0 in selected else np.isin(data['face_ids'],selected))&retained(data['xyz'],value.get('exclusions',[]))
    return meta,data,mask


def screen_one(value,history,cluster,cache):
    result=dict(target_key=value['target_key'],class_id=cluster['final_class_id'],class_name=cluster['final_class'],
        frame_id=cluster['frame_id'],group_id=cluster['group_id'],split=cluster['split'],domain=cluster['domain'],
        class_assignment=cluster['classification_source'],class_assignment_review_required=cluster.get('classification_review_required',False),
        original_appearance_class=cluster.get('original_appearance_class'),geometry_candidate=cluster.get('geometry_candidate'),
        revision=value['revision'],state=value['state'],human_pose_confirmed=value.get('human_pose_confirmed',False),
        source_review_sha256=hashlib.sha256(canonical(value)).hexdigest(),robot_command_eligible=False)
    if value['state']=='deleted':return dict(result,eligible=False,screen_status='deleted_audit_only')
    if not value.get('ruler') or not value.get('geometry_token') or not value.get('selected_faces'):
        return dict(result,eligible=False,screen_status='missing_ruler_geometry_or_selected_faces')
    try:
        meta,data,mask=load_geometry(value,cache);p=data['xyz'][mask]
        if len(p)<3:raise ValueError('fewer_than_3_selected_points')
        c,b=world_ruler(value['ruler']);local=(p-c)@b
        lo,hi=np.quantile(local,[.01,.99],axis=0);mean=local.mean(axis=0);median=np.median(local,axis=0)
        middle=np.array([(lo[0]+hi[0])/2,median[1],median[2]])
        width=float(hi[0]-lo[0]);label_width=2*value['ruler']['half_width'];denom=max(label_width,width,1e-6)
        h=history_evidence(value,history)
        candidate=next((x for x in meta['candidates'] if x['id'] in value['selected_faces']),meta['manual'])
        candidate_offset=(np.asarray(candidate['center'])-c)@b
        flags=[]
        if abs(mean[0]-middle[0])>max(.025,.04*denom):flags.append('density_center_differs_from_visible_extent_midpoint')
        if abs(middle[0])>max(.03,.05*denom):flags.append('label_differs_from_visible_extent_midpoint_not_necessarily_wrong')
        if max(abs(lo[0]+label_width/2),abs(hi[0]-label_width/2))>max(.05,.1*denom):flags.append('ruler_endpoints_differ_from_visible_extent')
        spread=float(np.quantile(local[:,1],.9)-np.quantile(local[:,1],.1))
        if spread>max(.04,.05*denom):flags.append('selected_depth_spread_check_background_or_multiple_faces')
        total=int(data['mask'].sum());valid_fraction=len(data['xyz'])/max(total,1)
        if valid_fraction<.5:flags.append('many_polygon_pixels_without_usable_depth')
        if 0 in value['selected_faces']:flags.append('manual_all_roi_check_background')
        if cluster.get('crop_touches_image_edge'):flags.append('image_edge_truncation_candidate')
        if cluster.get('classification_review_required'):flags.append('class_assignment_needs_review')
        if value.get('axes_interpretation'):flags.append('axis_revision_width_and_angle_need_review')
        if not value['sensor']['axes_confirmed']:flags.append('source_axes_not_target_confirmed')
        if abs(candidate_offset[0])>.005:flags.append('label_center_differs_from_current_candidate_seed')
        result.update(eligible=True,screen_status='ok',geometry_token=value['geometry_token'],geometry_npz_sha256=meta['full_resolution_artifact_sha256'],
            selected_points=len(p),region_points=len(data['xyz']),selected_count_matches_record=len(p)==value.get('selected_measured_points'),
            usable_depth_pixel_fraction=valid_fraction,label_width_m=label_width,visible_width_m=width,
            point_mean_local_m=mean.tolist(),point_median_local_m=median.tolist(),visible_quantile_midpoint_local_m=middle.tolist(),
            visible_quantile_bounds_local_m=[lo.tolist(),hi.tolist()],candidate_center_local_m=candidate_offset.tolist(),
            selected_depth_p10_p90_m=spread,metric=value['sensor']['scale_to_m'] is not None,
            density_shift_width_fraction=float(abs(mean[0]-middle[0])/denom),
            label_to_visible_midpoint_width_fraction=float(abs(middle[0])/denom),
            history=h,screen_flags=flags,support_hypothesis=support_hypothesis(local),
            hard_score=float(abs(mean[0]-middle[0])/denom+abs(middle[0])/denom+spread/denom+(.3 if valid_fraction<.5 else 0)+(.15 if h['multiple_human_saves_with_geometric_change'] else 0)))
    except (ValueError,KeyError,OSError) as exc:result.update(eligible=False,screen_status=str(exc))
    return result


def diverse_pick(candidates,n,*,seed,score=False,used=None):
    used=set(used or []);items=[r for r in candidates if r['target_key'] not in used]
    rng=np.random.default_rng(seed);order={r['target_key']:float(rng.random()) for r in sorted(items,key=lambda x:x['target_key'])}
    groups=Counter();frames=set();chosen=[]
    while items and len(chosen)<n:
        items.sort(key=lambda r:(r['frame_id'] in frames,groups[r['group_id']],-r['hard_score'] if score else order[r['target_key']],r['target_key']))
        r=items.pop(0);chosen.append(r);groups[r['group_id']]+=1;frames.add(r['frame_id'])
    return chosen


def sample_pool(pool,classes,current,seed=20261022):
    samples=[];coverage=[]
    for cid in range(1,23):
        all_class=[r for r in classes.values() if r['final_class_id']==cid]
        saved=[r for r in pool if r['class_id']==cid];eligible=[r for r in saved if r['eligible']]
        selected=[]
        if len(eligible)<=12:
            selected=[dict(r,sample_role='all_available_saved') for r in sorted(eligible,key=lambda r:r['target_key'])]
        else:
            random=diverse_pick(eligible,6,seed=seed+cid)
            hard=diverse_pick(eligible,6,seed=seed+100+cid,score=True,used={r['target_key'] for r in random})
            selected=[dict(r,sample_role='group_balanced_random') for r in random]+[dict(r,sample_role='targeted_difficult') for r in hard]
        if not eligible:
            available=[dict(r,hard_score=0.) for r in all_class if r['target_key'] not in current]
            selected=[dict(target_key=r['target_key'],class_id=cid,class_name=r['final_class'],frame_id=r['frame_id'],group_id=r['group_id'],
                split=r['split'],domain=r['domain'],sample_role='unannotated_context_no_human_label',eligible=False,screen_status='no_saved_human_pose',
                class_assignment=r['classification_source'],class_assignment_review_required=r.get('classification_review_required',False),
                original_appearance_class=r.get('original_appearance_class'),robot_command_eligible=False)
                for r in diverse_pick(available,6,seed=seed+cid)]
        samples+=selected
        coverage.append(dict(class_id=cid,total=len(all_class),saved=len(saved),deleted=sum(r['state']=='deleted' for r in saved),
            usable_saved=len(eligible),geometrically_revised=sum(r.get('history',{}).get('multiple_human_saves_with_geometric_change',False) for r in eligible),
            confirmed=sum(r.get('human_pose_confirmed',False) for r in eligible),sampled_saved=sum(r['eligible'] for r in selected),
            sampled_unannotated=sum(not r['eligible'] for r in selected)))
    return samples,coverage


def screen(out):
    manifest=json.loads((out/'snapshot/manifest.json').read_text());current,histories=read_snapshot(out)
    classes={r['target_key']:r for r in rows(out/'snapshot/classes.jsonl')}
    if set(current)-set(classes):raise ValueError('Saved target absent from clustering identity mapping')
    items=sorted(current)
    def one(key):return screen_one(current[key],histories[key],classes[key],LIVE/'geometry')
    with ThreadPoolExecutor(max_workers=6) as executor:pool=list(executor.map(one,items))
    write_rows(out/'screening.jsonl',pool)
    samples,coverage=sample_pool(pool,classes,current)
    for i,r in enumerate(samples,1):r['case_id']=f'C{r["class_id"]:02d}-{sum(s["class_id"]==r["class_id"] for s in samples[:i]):02d}'
    write_rows(out/'samples.jsonl',samples);write_json(out/'coverage.json',coverage)
    write_json(out/'sampling_policy.json',dict(seed=20261022,classes='final_class_id 1..22; original A/geometry/outlier flags retained',
        per_class_saved_maximum=12,random=6,difficult=6,short_classes='all_available',no_saved_classes='6 unannotated context examples, never labelled corrected',
        random_policy='fixed_seed_group_balanced_random_not_simple_random',hard_policy='group_diverse_visible_density_shift_extent_mismatch_depth_spread_missing_depth_and_geometric_revisions',
        prevalence_claims_allowed=False,physical_full_face_reference_inferred_from_point_center=False))
    print(json.dumps(dict(stage='screen',saved=len(current),eligible=sum(r['eligible'] for r in pool),samples=len(samples),coverage=coverage),ensure_ascii=False),flush=True)


def svg_plot(local,record,plane,*,reference=None):
    """Equal physical scaling; no perspective/3D center copied into image pixels."""
    W,H=500,280;pad=[46,12,28,32];j=2 if plane=='front' else 1
    width=record.get('label_width_m');qs=np.quantile(local[:,[0,j]],[.005,.995],axis=0)
    xmin=min(qs[0,0],-width/2 if width else 0);xmax=max(qs[1,0],width/2 if width else 0)
    ymin=min(qs[0,1],0);ymax=max(qs[1,1],0);span=max(xmax-xmin,ymax-ymin,.1)
    xmin-=span*.08;xmax+=span*.08;ymin-=span*.08;ymax+=span*.08
    scale=min((W-pad[0]-pad[1])/(xmax-xmin),(H-pad[2]-pad[3])/(ymax-ymin));cx=(xmin+xmax)/2;cy=(ymin+ymax)/2
    def pixel(x,y):return (pad[0]+(W-pad[0]-pad[1])/2+(x-cx)*scale,pad[2]+(H-pad[2]-pad[3])/2-(y-cy)*scale)
    out=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" role="img" aria-label="{plane} equal scale measured cloud">',
         '<rect width="100%" height="100%" fill="#f7f9fd"/>']
    def line(x,color,dash='5 3'):
        px,_=pixel(x,0);out.append(f'<path d="M{px:.2f},{pad[2]}V{H-pad[3]}" stroke="{color}" stroke-width="1.8" stroke-dasharray="{dash}"/>')
    for x in np.linspace(xmin,xmax,5):
        px,_=pixel(x,0);out.append(f'<path d="M{px:.1f},{pad[2]}V{H-pad[3]}" stroke="#dfe5ef"/><text x="{px:.1f}" y="{H-14}" font-size="10" text-anchor="middle">{x:.2f}</text>')
    for y in np.linspace(ymin,ymax,4):
        _,py=pixel(0,y);out.append(f'<path d="M{pad[0]},{py:.1f}H{W-pad[1]}" stroke="#dfe5ef"/><text x="3" y="{py:.1f}" font-size="10">{y:.2f}</text>')
    indices=np.arange(len(local));
    if len(indices)>1800:indices=np.sort(np.random.default_rng(42).choice(indices,1800,replace=False))
    path=' '.join(f'M{x:.1f},{y:.1f}h.5' for i in indices for x,y in [pixel(local[i,0],local[i,j])])
    out.append(f'<path d="{path}" fill="none" stroke="#718cac" stroke-width="2" opacity=".55"/>')
    for field,color in [('point_mean_local_m','#d77700'),('point_median_local_m','#b843b3'),('visible_quantile_midpoint_local_m','#267bd9')]:
        if record.get(field):line(record[field][0],color)
    if record.get('previous_center_local_m'):line(record['previous_center_local_m'][0],'#697386','2 4')
    if reference:
        a,b=reference['center_width_interval_m'];x1,_=pixel(a,0);x2,_=pixel(b,0)
        out.append(f'<rect x="{min(x1,x2):.2f}" y="{pad[2]}" width="{max(abs(x2-x1),2):.2f}" height="{H-pad[2]-pad[3]}" fill="#007d6733"/>');line(reference['center_width_m'],'#007d67')
    if width:
        line(0,'#d22e43','');a=pixel(-width/2,0);b=pixel(width/2,0)
        out.append(f'<path d="M{a[0]:.1f},{a[1]:.1f}L{b[0]:.1f},{b[1]:.1f}" stroke="#d22e43" stroke-width="3"/>')
        x,y=pixel(0,0);out.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="5" fill="white" stroke="#d22e43" stroke-width="2"/>')
    out.append(f'<text x="12" y="17" font-size="12">{plane}: W / {"H" if plane=="front" else "D"} [m], equal scale</text></svg>')
    return ''.join(out)


def case_data(out,sample,current,sources,classes,engine,units,axes):
    key=sample['target_key'];source=sources[sample['frame_id']];cluster=classes[key];w,h=source['size']
    path=Path(source['source_paths']['pcd']);assert digest(path)==source['source_anchor_hash']
    assert digest(Path(json.loads((out/'snapshot/manifest.json').read_text())['formal'])/source['image'])==source['files'][source['image']]
    if sample['eligible']:
        value=current[key];meta,data,mask=load_geometry(value,LIVE/'geometry');center,b=world_ruler(value['ruler'])
        assert np.array_equal(data['polygon'],np.asarray(value['polygon']))
        p=data['xyz'][mask];uv=data['uv'][mask];r=value
    else:
        box=cluster['bbox'];x,y,bw,bh=(box[k] for k in ('x','y','width','height'));poly=[[x,y],[x+bw,y],[x+bw,y+bh],[x,y+bh]]
        sensor=axes.sensor(units.sensor(None,source),source)
        meta=engine.compute(key,source,poly,sensor);c=meta['candidates'][0] if meta['candidates'] else meta['manual']
        with np.load(engine.cache/(meta['token']+'.npz'),allow_pickle=False) as z:data={k:z[k].copy() for k in z.files}
        mask=np.ones(len(data['xyz']),bool) if c['id']==0 else data['face_ids']==c['id'];p=data['xyz'][mask];uv=data['uv'][mask]
        center=np.asarray(c['center']);b=np.asarray(c['basis'])
        r=dict(polygon=poly,sensor=sensor,selected_faces=[c['id']],ruler=None,pose=None)
    _,native=read_pcd(path)
    ids=data['source_indices'];scale=r['sensor']['scale_to_m'];assert scale is not None
    np.testing.assert_allclose(data['xyz'],native[ids,:3].astype(float)*scale,rtol=1e-7,atol=1e-8)
    mapping=orient_grid(np.arange(w*h).reshape(h,w),source['sensor_policy'])
    np.testing.assert_array_equal(mapping[data['uv'][:,1],data['uv'][:,0]],ids)
    local=(p-center)@b
    return r,local,uv,source,dict(pcd_sha256=source['source_anchor_hash'],image_sha256=source['files'][source['image']],
        geometry_npz_sha256=meta['full_resolution_artifact_sha256'],geometry_token=meta['token'],selected_source_indices_preserved=True,
        source_pixel_rotation_degrees=source['pixel_rotation_degrees'],source_scale_to_m=scale,sensor=r['sensor'])


def prepare(out):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    manifest=json.loads((out/'snapshot/manifest.json').read_text());formal=Path(manifest['formal']);_,sources=load_dataset(formal)
    current,_=read_snapshot(out);classes={r['target_key']:r for r in rows(out/'snapshot/classes.jsonl')};samples=rows(out/'samples.jsonl')
    assets=out/'assets';assets.mkdir(exist_ok=True);(out/'cases').mkdir(exist_ok=True);(out/'contact_sheets').mkdir(exist_ok=True)
    units=MetrePolicy.load(PROJECT/'configs/pallet_pose_review_units_v1.json',formal);axes=AxesPolicy.load(PROJECT/'configs/pallet_pose_review_axes_v1.json',formal)
    engine=GeometryEngine(formal,out/'derived_geometry');font=ImageFont.truetype(str(FONT),15)
    for cid in range(1,23):
        group=[r for r in samples if r['class_id']==cid];tiles=[]
        for sample in group:
            sample=copy.deepcopy(sample)
            r,local,uv,source,evidence=case_data(out,sample,current,sources,classes,engine,units,axes)
            previous=sample.get('history',{}).get('previous')
            if previous and r.get('ruler'):
                center,b=world_ruler(r['ruler']);sample['previous_center_local_m']=((np.asarray(previous['center_source'])-center)@b).tolist()
            key=sample['target_key'];image=Image.open(formal/source['image']).convert('RGB')
            original=io.BytesIO();image.save(original,format='PNG');(assets/(key+'_original.png')).write_bytes(original.getvalue())
            poly=np.array(r['polygon']);lo=np.floor(poly.min(0)-[12,10]).astype(int);hi=np.ceil(poly.max(0)+[12,10]).astype(int)
            lo=np.maximum(lo,0);hi=np.minimum(hi,[image.width,image.height]);cropbox=[int(lo[0]),int(lo[1]),int(hi[0]),int(hi[1])]
            draw=ImageDraw.Draw(image);draw.line([tuple(p) for p in np.r_[poly,poly[:1]]],fill='#00bac9',width=max(1,image.width//320))
            crop=image.crop(cropbox);crop.save(assets/(key+'_crop.png'))
            for plane in ('front','top'):(assets/(key+'_'+plane+'.svg')).write_text(svg_plot(local,sample,plane))
            # Small contact sheets are for analyst visual inspection, not GT.
            fig,axs=plt.subplots(1,2,figsize=(6,1.6),layout='constrained')
            for ax,j,title in [(axs[0],2,'front W/H'),(axs[1],1,'top W/D')]:
                ax.scatter(local[:,0],local[:,j],s=.6,c='#6485a8');ax.axvline(0,c='#d22e43' if sample['eligible'] else '#7c8796',lw=1)
                for field,color in [('point_mean_local_m','#d77700'),('point_median_local_m','#b843b3'),('visible_quantile_midpoint_local_m','#267bd9')]:
                    if sample.get(field):ax.axvline(sample[field][0],c=color,lw=.8,ls='--')
                if sample.get('label_width_m'):ax.plot(np.array([-1,1])*sample['label_width_m']/2,[0,0],c='#d22e43',lw=2)
                ax.set_aspect('equal',adjustable='datalim');ax.tick_params(labelsize=6);ax.set_title(title,fontsize=8);ax.grid(alpha=.2)
            buf=io.BytesIO();fig.savefig(buf,dpi=95);plt.close(fig);buf.seek(0);plot=Image.open(buf).convert('RGB');plot.thumbnail((450,125))
            tile=Image.new('RGB',(470,300),'white');d=ImageDraw.Draw(tile)
            label='人工保存草稿' if sample['eligible'] else '无人工标注，仅机器区域'
            d.text((8,3),sample['case_id']+' '+label,font=font,fill='#183044')
            d.text((8,23),key[:12]+' · '+source['split']+' · '+sample['domain'],font=font,fill='#526478')
            crop.thumbnail((450,120));tile.paste(crop,((470-crop.width)//2,47))
            tile.paste(plot,((470-plot.width)//2,171))
            tiles.append(tile)
            write_json(out/'cases'/(key+'.json'),dict(sample=sample,review=r if sample['eligible'] else None,evidence=evidence,
                crop_box=cropbox,local_center_source=(world_ruler(r['ruler'])[0].tolist() if r.get('ruler') else None),
                analyst_review_status='automatic_screen_only_pending_visual_analysis',robot_command_eligible=False))
        cols=3;board=Image.new('RGB',(cols*470,math.ceil(len(tiles)/cols)*300+40),'#dce5ef');draw=ImageDraw.Draw(board)
        legend='红=标注，橙=均值，紫=中位数，蓝=可见范围中点；均非真值' if any(s['eligible'] for s in group) else '无人工位姿；灰线仅机器坐标原点，不是人工标注'
        draw.text((10,8),f'Class {cid} · '+legend,font=font,fill='#183044')
        for i,tile in enumerate(tiles):board.paste(tile,((i%cols)*470,40+(i//cols)*300))
        board.save(out/'contact_sheets'/f'class_{cid:02d}.jpg',quality=92)
        print(json.dumps(dict(stage='prepare',class_id=cid,cases=len(group))),flush=True)


def measure_patches(native,mapping,ruler,scale,patches,plane_depth=0.,tolerance=.04,selected_ids=()):
    """Explicit analyst edge patches -> uncertain, non-GT width reference.

    Measurement uses actual pixel-indexed points, not an image midpoint or
    a completed/symmetrized cloud. No valid edge -> no reference.
    """
    center,b=world_ruler(ruler);measurements={}
    for name,box in patches.items():
        x0,y0,x1,y1=box
        ids=mapping[y0:y1,x0:x1].ravel();ids=ids[valid_xyz(native[ids,:3])]
        local=(native[ids,:3].astype(float)*scale-center)@b
        near=np.abs(local[:,1]-plane_depth)<=tolerance;p=local[near]
        measurements[name]=dict(patch_pixels=box,total_valid_points=len(local),near_face_points=len(p),
            near_face_selected_points=int(np.isin(ids[near],selected_ids).sum()),
            within_10mm_of_current_face_points=int((np.abs(local[:,1]-plane_depth)<=.01).sum()),
            width_interval_m=np.quantile(p[:,0],[.05,.95]).tolist() if len(p)>=3 else None,
            depth_median_m=float(np.median(p[:,1])) if len(p)>=3 else None)
    left,right=measurements['left'],measurements['right'];reference=None
    if left['width_interval_m'] is not None and right['width_interval_m'] is not None:
        # A visually identified pair of physical bounds is required by the
        # input protocol; availability alone does not grant reference status.
        a=left['width_interval_m'];z=right['width_interval_m']
        low=(min(a)+min(z))/2;high=(max(a)+max(z))/2
        midpoint=(low+high)/2
        # Sensitivity allowance, NOT a calibrated confidence interval.
        margin=.015;low-=margin;high+=margin
        reference=dict(center_width_m=midpoint,center_width_interval_m=[low,high],
            additional_boundary_localization_allowance_m=margin,interval_is_statistical_confidence_interval=False,
            label_minus_reference_width_m=-midpoint,
            label_minus_reference_width_interval_m=[-high,-low],
            source='analyst_selected_visible_outer_edge_patches_measured_in_source_cloud_not_GT',
            angle_independently_verified=False,robot_command_eligible=False)
        middle=measurements.get('middle_leg')
        if middle and middle['width_interval_m']:
            a,z=middle['width_interval_m'];reference['middle_leg_visible_patch_center_width_m']=(a+z)/2
            reference['middle_leg_patch_minus_face_reference_width_m']=(a+z)/2-reference['center_width_m']
    return dict(patches=measurements,reference=reference,status='bounded_analysis_reference_not_GT' if reference else 'insufficient_measured_edge_evidence')


def measure(out):
    manifest=json.loads((out/'snapshot/manifest.json').read_text());formal=Path(manifest['formal']);_,sources=load_dataset(formal)
    current,_=read_snapshot(out);samples={r['case_id']:r for r in rows(out/'samples.jsonl')}
    config=json.loads((PROJECT/'configs/pallet_pose_annotation_audit_v1_reviews.json').read_text());result={}
    for case_id,spec in config['boundary_patch_cases'].items():
        sample=samples[case_id];source=sources[sample['frame_id']];_,native=read_pcd(source['source_paths']['pcd']);w,h=source['size']
        mapping=orient_grid(np.arange(w*h).reshape(h,w),source['sensor_policy']);value=current[sample['target_key']]
        _,data,selection=load_geometry(value,LIVE/'geometry')
        measured=measure_patches(native,mapping,value['ruler'],value['sensor']['scale_to_m'],spec['patches'],
            plane_depth=sample['point_median_local_m'][1],selected_ids=data['source_indices'][selection])
        result[case_id]=dict(measured,definition=spec['definition'],target_key=sample['target_key'],evidence_level='analyst_reading_plus_measured_source_points_not_blind_GT')
        image=Image.open(out/'assets'/(sample['target_key']+'_original.png')).convert('RGB');draw=ImageDraw.Draw(image)
        for name,box in spec['patches'].items():draw.rectangle(box,outline='#00bb88' if name in ('left','right') else '#d55ad0',width=2)
        image.save(out/'assets'/(sample['target_key']+'_reference_patches.png'))
    write_json(out/'manual_reference_measurements.json',result)
    print(json.dumps(dict(stage='measure',cases=len(result),bounded_references=sum(v['reference'] is not None for v in result.values()))),flush=True)


TAG_NAMES=dict(density_bias='密度中心偏移',reference_ambiguity='参考中心需区分',control_complete='较完整对照',
    visibility_loss='保存点云覆盖不完整',selection_omission='原始点存在但选面未覆盖',polygon_vs_face='二维修订≠三维完整',
    background_depth='检查开口后方回波',oblique_view='斜视/投影问题',insufficient_reference='完整边界证据不足',
    no_middle_leg_template='不能套用中间腿模板',low_image_quality='强度图质量低',insufficient_coverage='类别标注覆盖不足',
    stacked_layer='堆叠层身份',coverage_gap='无人工位姿记录',partial_selection='局部自动候选',component_identity='分量不等于腿身份',
    automatic_screen_only='自动线索，非错误结论')
FLAG_NAMES=dict(density_center_differs_from_visible_extent_midpoint='点均值与可见范围中点不同',
    label_differs_from_visible_extent_midpoint_not_necessarily_wrong='标注与可见范围中点不同（不自动判错）',
    ruler_endpoints_differ_from_visible_extent='标尺端点与可见范围不一致',selected_depth_spread_check_background_or_multiple_faces='选面深度分散，查背景/多面',
    many_polygon_pixels_without_usable_depth='区域中可用深度较少',manual_all_roi_check_background='手动全ROI，需排背景',
    image_edge_truncation_candidate='原图边缘截断候选',class_assignment_needs_review='类别分配待复核',
    axis_revision_width_and_angle_need_review='轴向修订后的宽度/角度待复核',source_axes_not_target_confirmed='目标轴向尚未人工确认',
    label_center_differs_from_current_candidate_seed='当前中心不同于候选初值')


def case_action(tags):
    if 'coverage_gap' in tags:return '先补该类人工标尺与选面记录，再评价人工标注；机器候选不升级为GT。'
    if 'selection_omission' in tags:return '回查对应原始像素与所有面候选；必要时合并属于同一叉取面的支撑片，再独立核对完整外边界。不要直接把中心移到剩余点群。'
    if 'background_depth' in tags:return '将开口前表面与孔后回波分开，检查深度残差、选面及剔除范围，然后再标注中心与方向。'
    if 'visibility_loss' in tags:return '先区分原生深度缺失与选面遗漏；双侧物理边界可辨时用边界参照，否则保留中心区间或待判断。'
    if 'no_middle_leg_template' in tags or 'component_identity' in tags:return '按实际观察面的物理边界定义中心；没有可辨认中间腿时不强制三腿结构，不从直方图分量自动命名托盘腿。'
    return '独立核对同一叉取面的左右外边界、开口和支撑身份；点均值、中位数、可见范围中点仅作为诊断，不作为正确标签判据。'


def report_font(out,text):
    from fontTools import subset
    from fontTools.ttLib import TTFont
    font=TTFont(FONT);options=subset.Options();options.flavor='woff';options.name_IDs=['*']
    sub=subset.Subsetter(options=options);sub.populate(text=text);sub.subset(font)
    for name in font['name'].names:
        if name.nameID in (1,4,6):name.string='AnnotationAuditCJK'.encode('utf-16-be') if name.isUnicode() else b'AnnotationAuditCJK'
    font.flavor='woff';font.save(out/'assets/report_font.woff')
    shutil.copyfile(PROJECT/'pallet/assets/FONT_LICENSE.txt',out/'FONT_LICENSE.txt')


def render(out):
    manifest=json.loads((out/'snapshot/manifest.json').read_text());samples=rows(out/'samples.jsonl');pool=rows(out/'screening.jsonl')
    config_path=PROJECT/'configs/pallet_pose_annotation_audit_v1_reviews.json';config=json.loads(config_path.read_text())
    refs=json.loads((out/'manual_reference_measurements.json').read_text());coverage=json.loads((out/'coverage.json').read_text())
    current,histories=read_snapshot(out);cases=[]
    for sample in samples:
        key=sample['target_key'];path=out/'cases'/(key+'.json');case=json.loads(path.read_text());s=case['sample'];cid=s['case_id']
        observation=config['case_observations'].get(cid)
        if observation:tags=observation['tags'];note=observation['note']
        else:
            tags=['automatic_screen_only'];note=config['class_observations'][str(s['class_id'])]
            if not s['eligible']:tags=['coverage_gap'];note='该案例没有已保存人工位姿，只用于检查可标注性，不参与标注偏差或修正质量评价。'
        case.update(tags=tags,note=note,action=case_action(tags),scope='联系表整体视觉检查；指定重点案例另有原生像素/点云检查。'+(' 本例有单独观察记录。' if observation else ' 本例未单独给出标注对错定论。'),
            reference=refs.get(cid),analyst_review_status='focused_qualitative_review' if observation else 'contact_sheet_inspected_with_automatic_metrics',
            no_automatic_label_correction=True)
        if s['eligible']:
            value=current[key];_,data,mask=load_geometry(value,LIVE/'geometry');center,b=world_ruler(value['ruler']);local=(data['xyz'][mask]-center)@b
            for plane in ('front','top'):(out/'assets'/(key+'_'+plane+'.svg')).write_text(svg_plot(local,s,plane,reference=(refs.get(cid) or {}).get('reference')))
        write_json(path,case);cases.append(case)
    eligible=[r for r in pool if r['eligible']];saved=[c for c in cases if c['sample']['eligible']]
    diagnostics=Counter(f for r in eligible for f in r['screen_flags']);sample_diagnostics=Counter(f for c in saved for f in c['sample']['screen_flags'])
    confirmed=sum(r['human_pose_confirmed'] for r in eligible);revised=sum(c['sample'].get('history',{}).get('multiple_human_saves_with_geometric_change',False) for c in saved)
    summary=dict(created_at=now(),snapshot_created_at=manifest['created_at'],saved_targets=manifest['saved_targets'],snapshot_events=manifest['events'],
        usable_saved=len(eligible),deleted=sum(r['state']=='deleted' for r in pool),missing_required_fields=sum(r['screen_status']=='missing_ruler_geometry_or_selected_faces' for r in pool),
        classes=22,sample_cases=len(cases),sample_saved=len(saved),sample_historically_revised=revised,sample_unannotated=len(cases)-len(saved),
        sample_roles=dict(Counter(c['sample']['sample_role'] for c in cases)),confirmed_poses_in_eligible_pool=confirmed,
        no_saved_classes=[c['class_id'] for c in coverage if not c['saved']],focused_qualitative_cases=sum(c['analyst_review_status']=='focused_qualitative_review' for c in cases),
        measured_patch_cases=len(refs),screening_counts=dict(diagnostics),sample_screening_counts=dict(sample_diagnostics),
        inference='descriptive_nonblind_audit_not_error_rate_not_independent_accuracy',source_annotation_writes=0,robot_command_eligible=False)
    write_json(out/'findings.json',dict(summary=summary,class_observations=config['class_observations'],case_observations=config['case_observations'],
        manual_references=refs,flags_are_diagnostics_not_errors=True))
    write_rows(out/'selected_reviews.jsonl',(current[c['sample']['target_key']] for c in saved))
    write_rows(out/'selected_histories.jsonl',(dict(target_key=c['sample']['target_key'],events=histories[c['sample']['target_key']]) for c in saved))
    fields=['case_id','target_key','class_id','sample_role','revision','historical_geometric_revision','issue_tags','label_width_m',
        'point_mean_W_mm','point_median_W_mm','visible_midpoint_W_mm','reference_label_delta_W_mm','reference_label_delta_low_W_mm','reference_label_delta_high_W_mm',
        'note','recommended_action','label_status','robot_command_eligible']
    text=io.StringIO(newline='');writer=csv.DictWriter(text,fieldnames=fields);writer.writeheader()
    for c in cases:
        s=c['sample'];ref=(c.get('reference') or {}).get('reference');row={k:s.get(k,'') for k in ('case_id','target_key','class_id','sample_role','revision','label_width_m')}
        row.update(historical_geometric_revision=s.get('history',{}).get('multiple_human_saves_with_geometric_change',False),issue_tags=';'.join(c['tags']),
            note=c['note'],recommended_action=c['action'],label_status='saved_draft_not_confirmed_GT' if s['eligible'] else 'no_human_pose',robot_command_eligible=False)
        for field,name in [('point_mean_local_m','point_mean_W_mm'),('point_median_local_m','point_median_W_mm'),('visible_quantile_midpoint_local_m','visible_midpoint_W_mm')]:
            row[name]=s[field][0]*1000 if s.get(field) else ''
        if ref:row.update(reference_label_delta_W_mm=ref['label_minus_reference_width_m']*1000,
            reference_label_delta_low_W_mm=ref['label_minus_reference_width_interval_m'][0]*1000,reference_label_delta_high_W_mm=ref['label_minus_reference_width_interval_m'][1]*1000)
        for k,v in row.items():
            if isinstance(v,str) and v.lstrip().startswith(('=','+','-','@')):row[k]="'"+v
        writer.writerow(row)
    (out/'sample_review_queue.csv').write_text('\ufeff'+text.getvalue())
    table='| 类别 | 全部目标 | 已保存 | 可用标尺 | 有几何修订历史 | 抽取保存/未标注 |\n|---|---:|---:|---:|---:|---:|\n'
    for c in coverage:table+=f'| Class {c["class_id"]} | {c["total"]} | {c["saved"]} | {c["usable_saved"]} | {c["geometrically_revised"]} | {c["sampled_saved"]}/{c["sampled_unannotated"]} |\n'
    findings='''## 主要发现

1. **三种中心不能混用。** 完整叉取面外宽中心、中间腿可见表面中心、可见点群的均值/中位数分别由边界、局部结构和采样密度决定。几何上不存在恒等关系。但完整对称样本中前两者也可能接近，不能预设每个中间腿参照都错。
2. **缺的不一定是原始点，也可能是选面。** C12-09左腿片带原始有效点156个，深度距当前面≤40mm点111个，选入0个；C09-07左腿片带对应42/31/0个，中间腿也有近面点未选入。阈值只是覆盖诊断，不能证明全部点同属一个精确平面。应先回查平面分割、合并选择和剔除，不能都归为视角导致相机无点。
3. **完整中心可能与残余点群中心相差数十厘米，却不能据此判标注错。** C09-07标注→保存选面中位数W为+411.4mm；C12-09为+464.6mm；C14-08为−489.4mm。这些数值是选面覆盖/密度诊断，不是标注真实误差。
4. **可见范围中点也不能解决单侧缺失。** 它比点均值少受密度影响，但丢掉一个端部后，范围本身就变短。例如C12-09可见范围中点偏+254.0mm，不能把它当完整外宽中点。
5. **二维轮廓修好不等于三维选面完整。** C05-08、C14-08、C15-07已经有明显轮廓修订，保存点云仍可能漏掉支撑片。开口内的二维像素也可能返回后方物体或地面，C07-07、C09-08、C15-08的俯视深度条带需优先排查。
6. **类别不是固定物理模板。** 同类仍混有不同观察面、斜视、堆叠和采集域；Class 3/8/16/18等有大开口或U形观察面，不能强制寻找中间腿。直方图中三个分量也可能是横梁断点，并不证明三条腿。
7. **部分标签无法在当前证据下判定对错。** 强斜视、边界截断、低分辨率和残余单侧点需要中心区间或待判断，不能根据类别中心、标尺初值或对称补全自动生成GT。

## 有边缘片带的局部量化（非GT）

沿当前标尺宽度轴，人工在原图选择外边缘片带，再按像素—源点索引查原始PCD。片带点的5%—95%范围传播到中点，并额外加±15mm定位敏感性余量。它不是统计置信区间，不包含完整的标定/角度误差预算；本轮不发布“标注错误率”或实机精度。

| 案例 | 标注减边缘片带中点（mm） | 分析区间（mm） | 解释 |
|---|---:|---:|---|
'''
    for cid,v in refs.items():
        ref=v['reference']
        if ref:
            lo,hi=ref['label_minus_reference_width_interval_m']
            findings+=f'| {cid} | {ref["label_minus_reference_width_m"]*1000:+.1f} | [{lo*1000:+.1f}, {hi*1000:+.1f}] | 非独立GT；边界定位允许范围 |\n'
        else:findings+=f'| {cid} | — | — | 无足够双侧实测边缘，不输出参照 |\n'
    findings+='\n这些片带对照没有证明对应标签必须随点中位数移动。C02-09右边缘只有3个近面点，参照尤其脆弱；中间腿片带不是完整腿的精确几何中心，不能将其差值宣传为系统性物理偏差。\n'
    protocol='''# 建议标注判定规则（分析建议，未改在线工具或标签）

1. 参考对象为当前目标层、当前叉取面的完整物理外宽，不是整堆托盘、检测框、可见点群或中间腿。
2. 先确认观察面、左右物理外边界及源坐标轴；三维外宽中点不能直接用透视图的像素中点替代。
3. 中间腿/开口中心仅是结构线索。未独立证明结构对称前，不据其替代完整外宽中心。
4. 将“二维可见、原生深度有效、位于选定面、属于当前目标”分开核查。原始点存在但未选入时，先查分割和选面，而不是移动标签去迎合残余点。
5. 双侧边界和同面关系可信时，可由边界定义宽度中心；只缺局部腿但上梁完整时，腿缺失不一定妨碍宽度定位。
6. 仅一侧边界可信时标注可接受中心区间或待判断，不自动镜像补全，不把类别规格/模型预测当测量真值。独立多视图仅在确证同一物体、完成配准后提供证据，不能仅凭同采集组强行合并。
7. 前表面与孔内后方回波分开；二维外轮廓含孔并不代表孔内回波属于叉取面。多个支撑片合并前检查面法向、深度及目标层身份。
8. 中心、总宽度、方向、可见性、边界依据应分别审核。宽度对称缩放以既定中心为锚，不会自动修正中心。完整旋转、未知高度和机器人外参不补0。
9. 建议以后在工具中增加左右边界锚点、边界可见性、缺失原因（原生无点/未选入/遮挡/裁边）和中心区间；本轮不实施这些UI改动。
10. 训练/评估时隔离待判断和强依赖机器初值的非盲草稿；原val/test不回流train，不用本轮看过的test重新选模型。所有研究结果保持robot_command_eligible=false。
'''
    report=f'# 托盘叉取面中心标注抽样审查\n\n冻结时间：{manifest["created_at"]}。在线标注持续变化，本报告只针对该快照。\n\n已保存{manifest["saved_targets"]}条；可用于几何筛查{len(eligible)}条，删除{summary["deleted"]}条，缺关键字段{summary["missing_required_fields"]}条。抽样{len(cases)}例：保存标尺{len(saved)}例，其中{revised}例可核实历史中心/角度/宽度修改；另{len(cases)-len(saved)}例无人工位姿。全部仍非正式确认GT。\n\n'+findings+'\n## 类别覆盖\n\n'+table+'\n## 各类观察\n\n'+''.join(f'### Class {cid}\n{note}\n\n' for cid,note in config['class_observations'].items())+'''## 统计口径与局限

- 分组均衡随机样本与定向困难样本分开保留；不足12个的类别全取，Class 11/13/17仅展示机器候选上下文。不是简单随机总体抽样，不估计错误率。
- 所有22张联系表均进行视觉查看，指定案例另外查原生像素及点云；其余案例的自动线索不等于人工判错。
- “历史几何修改”只计可比较轴向下，连续人工保存间中心/宽度变化>0.5mm或局部方向变化>0.05°。忽略自动单位/轴向修订，纯方向反转不在该保守计数中；首次保存即已修正的记录也可能未被计入。
- 当前单位解释及240×96轴向沿已授权版本，目标未确认轴向的记录仍标明待核对。分析中的点和多边形均绑定源PCD/图像哈希、原像素旋转和标注修订。正视图标尺的H=0是局部视图参考高度，不表示叉取高度已标为0；导出位姿中的未知高度仍为null。
- 本轮没有生成独立盲GT，没有证明实机叉取成功率，没有自动修正任何标签，也没有训练或更新模型。
'''
    (out/'REPORT_zh.md').write_text(report);(out/'annotation_guidelines_zh.md').write_text(protocol)
    def td(x):return '<td>'+escape(str(x))+'</td>'
    table_html='<div class="table-wrap"><table><tr>'+''.join('<th>'+x+'</th>' for x in ['类别','全量','保存','有效标尺','历史几何修改','抽样 保存/无标注','本类观察'])+'</tr>'
    for c in coverage:
        cid=c['class_id'];table_html+='<tr><td><button data-class="'+str(cid)+'">Class '+str(cid)+'</button></td>'+''.join(td(x) for x in [c['total'],c['saved'],c['usable_saved'],c['geometrically_revised'],str(c['sampled_saved'])+'/'+str(c['sampled_unannotated']),config['class_observations'][str(cid)]])+'</tr>'
    table_html+='</table></div>'
    diag_html='<div class="table-wrap"><table><tr><th>自动诊断线索（非错误判定）</th><th>全部可用草稿</th><th>抽样保存草稿</th></tr>'+''.join('<tr>'+td(FLAG_NAMES.get(k,k))+td(v)+td(sample_diagnostics[k])+'</tr>' for k,v in diagnostics.most_common())+'</table></div>'
    featured=['C02-03','C04-03','C02-09','C09-07','C12-09','C14-08','C15-08','C22-07']
    features='<ul class="featured">'+''.join('<li><button class="case-id-link" data-case="'+cid+'">'+cid+'</button> '+escape(config['case_observations'][cid]['note'])+'</li>' for cid in featured)+'</ul>'
    css=(PROJECT/'pallet/assets/pose_annotation_audit/report.css').read_text();js=(PROJECT/'pallet/assets/pose_annotation_audit/report.js').read_text()
    payload=json.dumps(dict(cases=cases,class_observations=config['class_observations'],tag_names=TAG_NAMES),ensure_ascii=False,allow_nan=False).replace('<','\\u003c')
    html=f'''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>托盘中心标注抽样审查 · 22类</title><style>{css}</style></head><body><main>
<header class="banner"><h1>完整叉取面中心，不是残余点群中心</h1><p>按22个外观类别抽样核查原图、人工保存草稿、实测点云及修订历史。</p><p class="muted">快照：{manifest['created_at']} · 类别归属含待复核机器分配 · 所有结论为非盲研究审查</p>
<div class="stats"><div class="stat"><b>{len(cases)}</b>抽样案例</div><div class="stat"><b>{len(saved)}</b>已有保存标尺</div><div class="stat"><b>{revised}</b>可核实历史几何修改</div><div class="stat"><b>{len(cases)-len(saved)}</b>无人工位姿上下文</div></div>
<p class="warning">红色标注线不是本报告认可的GT；橙/紫/蓝线也不是真值。“与点群中心不同”不能直接判标注错误。本轮不修改在线标注。</p>
<div class="downloads"><a href="REPORT_zh.md">中文报告</a><a href="sample_review_queue.csv" download>案例CSV</a><a href="findings.json" download>结论JSON</a><a href="selected_reviews.jsonl" download>抽样保存标注</a><a href="selected_histories.jsonl" download>抽样修订历史</a><a href="annotation_guidelines_zh.md">建议标注规则</a></div></header>
<section class="section"><h2>先区分三件事</h2><ol><li><b>完整外宽中心 ≠ 中间腿中心：</b>局部结构与完整边界没有必然恒等关系；对称完整样本中也可能接近。</li><li><b>可见点中心 ≠ 完整外宽中心：</b>密度、缺侧、遮挡和孔后回波会改变均值、中位数，甚至可见范围中点。</li><li><b>原生无点 ≠ 当前未选入：</b>C12-09左腿片带有156个原始有效点、111个距当前面≤40mm点，却有0个进入保存选面；C09-07也有类似现象。先查点的来源与选面，不盲目移动中心。</li></ol><p>Class 11、13、17尚无保存位姿；Class 8、19仅1条有效记录。类别号不能被当作已知型号或固定三腿模板。</p>{features}</section>
<section class="section"><h2>类别覆盖与视觉观察</h2>{table_html}<details><summary>全量自动筛查计数：只用于安排复核，不是错误率</summary>{diag_html}</details></section>
<section id="cases" class="section"><h2>逐例图册</h2><div class="legend"><span class="red">红：当前草稿中心/宽度</span><span class="orange">橙：点均值</span><span class="purple">紫：点中位数</span><span class="blue">蓝：可见范围中点</span><span class="green">绿：手选边缘片带参照区间，非GT</span><span>灰虚线：上一人工修订中心</span></div><p class="muted">所有三维差值沿当前标尺W/D方向，不将三维中心虚构投影到原图。正视图标尺的H=0仅为局部视图参考，不代表已标注叉取高度；未知高度保持null。离线解压后打开index.html。</p>
<div class="filters"><label>类别<select id="classFilter"><option value="">全部22类</option></select></label><label>记录<select id="roleFilter"><option value="">全部</option><option value="revised">有历史几何修改</option><option value="saved">已有保存标尺</option><option value="unannotated">无人工位姿</option></select></label><label>问题<select id="issueFilter"><option value="">全部观察类型</option></select></label><label>搜索<input id="query" placeholder="案例编号、目标ID或帧名"></label></div><p id="classNote" class="class-note"></p><p id="count"></p></section>
<div id="cards"></div><div class="pager"><button id="prevPage">上一页</button><button id="nextPage">下一页</button></div>
<footer>固定随机种子20261022；每类最多6个组间均衡随机＋6个困难定向样本，不足则全取。非概率抽样，不估计总体错误率。正式划分、原PCD、标注库和旧交付包均不修改。robot_command_eligible=false。字体许可见FONT_LICENSE.txt。</footer>
</main><script id="audit-data" type="application/json">{payload}</script><script>{js}</script></body></html>'''
    report_font(out,html+report+protocol+json.dumps(TAG_NAMES,ensure_ascii=False)+js)
    (out/'index.html').write_text(html)
    write_json(out/'report_manifest.json',dict(schema='pose_annotation_audit_report_v1',summary=summary,snapshot_db_sha256=manifest['snapshot_db_sha256'],
        classes_sha256=manifest['class_source_sha256'],analyst_notes_sha256=digest(config_path),
        audit_code_sha256=digest(__file__),report_html_sha256=digest(out/'index.html'),
        original_snapshot_preserved=True,model_or_label_updates=False,robot_command_eligible=False))
    print(json.dumps(dict(stage='render',html=str(out/'index.html'),cases=len(cases),saved=len(saved),revised=revised)),flush=True)


def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path,default=DEFAULT)
    parser.add_argument('--stage',choices=['freeze','screen','prepare','measure','render'],required=True);args=parser.parse_args()
    {'freeze':freeze,'screen':screen,'prepare':prepare,'measure':measure,'render':render}[args.stage](args.output.resolve())


if __name__=='__main__':main()
