"""Recompute width/group statistics and pair evidence; verify immutable inputs."""
from collections import Counter,defaultdict
from contextlib import closing
import argparse
import hashlib
import json
from pathlib import Path
import sqlite3
import sys
from zipfile import ZipFile,ZIP_DEFLATED

import numpy as np

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest,load_dataset,protected_snapshot
from pallet.pose_dimension_report import OUT,stats,pair_geometry
from pallet.pose_annotation_audit import LIVE,rows,read_snapshot,write_json,load_geometry
from pallet.pose_review_geometry import canonical


def main():
    parser=argparse.ArgumentParser();parser.add_argument('--package',action='store_true');args=parser.parse_args()
    out=OUT;manifest=json.loads((out/'snapshot/manifest.json').read_text());current,histories=read_snapshot(out)
    formal=Path(manifest['formal']);_,sources=load_dataset(formal)
    assert digest(out/'snapshot/reviews.sqlite3')==manifest['snapshot_db_sha256']
    assert digest(out/'snapshot/classes.jsonl')==manifest['class_source_sha256']
    for path,sha in manifest['protected_inputs'].items():assert digest(PROJECT/path)==sha,path
    assert protected_snapshot(formal)==json.loads((out/'snapshot/protected_formal.json').read_text())
    records=rows(out/'width_records.jsonl');classes={r['target_key']:r for r in rows(out/'snapshot/classes.jsonl')}
    expected=[v for v in current.values() if v['state']!='deleted' and v.get('ruler') and v['sensor']['scale_to_m'] is not None and np.isfinite(v['ruler']['half_width']) and v['ruler']['half_width']>0]
    assert {r['target_key'] for r in records}=={v['target_key'] for v in expected}
    for r in records:
        v=current[r['target_key']]
        assert r['width_m']==2*v['ruler']['half_width'] and r['revision']==v['revision']
        assert r['class_id']==classes[r['target_key']]['final_class_id'] and r['height_m'] is None
        assert r['source_review_sha256']==hashlib.sha256(canonical(v)).hexdigest()
        assert not r['robot_command_eligible']
    summary=json.loads((out/'class_summary.json').read_text())
    for c in summary:
        rs=[r for r in records if r['class_id']==c['class_id']];assert stats(rs)==c['all']
        if rs:
            groups=defaultdict(list)
            for r in rs:groups[r['group_id']].append(r['width_m'])
            assert float(np.median([np.median(v) for v in groups.values()]))==c['all']['group_balanced_median_m']
        assert stats([r for r in rs if r['lower_risk_revised']])==c['lower_risk_revised']
        assert c['physical_length_m'] is None and c['physical_width_m'] is None
    for r in rows(out/'strata.jsonl'):
        check=stats([v for v in records if v['class_id']==r['class_id'] and str(v[r['stratum_field']])==r['stratum_value']])
        assert all(r[k]==v for k,v in check.items())
    candidates=rows(out/'adjacent_face_candidates.jsonl');samples=rows(out/'reviewed_pairs.jsonl');assets=[]
    for p in candidates:
        check=pair_geometry(*(current[k] for k in p['keys']));assert check['candidate_pass']
        assert all(p[k]==v for k,v in check.items())
    seen=set()
    for p in samples:
        a,b=(current[k] for k in p['keys']);assert a['source']['frame_id']==b['source']['frame_id']==p['frame_id']
        assert p['widths_m']==[2*a['ruler']['half_width'],2*b['ruler']['half_width']]
        if p['visual_review']['status']=='visually_supported_same_pallet_candidate':assert p['reported_dimensions_m']==sorted(p['widths_m'],reverse=True)
        else:assert p['reported_dimensions_m'] is None
        for v in (a,b):
            if v['target_key'] in seen:continue
            seen.add(v['target_key']);source=sources[v['source']['frame_id']]
            assert digest(source['source_paths']['pcd'])==source['source_anchor_hash']
            assert digest(formal/source['image'])==source['files'][source['image']]
            load_geometry(v,LIVE/'geometry')
    with closing(sqlite3.connect((LIVE/'annotations.sqlite3').resolve().as_uri()+'?mode=ro',uri=True)) as db:
        events={(k,r):v for k,r,v in db.execute('select target_key,revision,payload from events')}
    for key,hs in histories.items():
        for v in hs:assert events[key,v['revision']]==canonical(v).decode()
    result=json.loads((out/'results.json').read_text());assert result['code_sha256']==digest(PROJECT/'pallet/pose_dimension_report.py')
    assert result['pair_review_sha256']==digest(PROJECT/'configs/pallet_pose_dimensions_v1_pair_reviews.json')
    acceptance=dict(state='passed',valid_widths_recomputed=len(records),classes=22,subgroup_stats_recomputed=len(rows(out/'strata.jsonl')),
        pair_candidates_recomputed=len(candidates),visual_pairs_checked=len(samples),visually_supported_candidates=sum(p['reported_dimensions_m'] is not None for p in samples),
        pair_source_geometries_and_PCDs_verified=len(seen),protected_formal_files_unchanged=len(json.loads((out/'snapshot/protected_formal.json').read_text())),
        live_historical_events_preserved=sum(map(len,histories.values())),no_height_or_unverified_full_dimensions_invented=True,source_annotation_writes=0)
    write_json(out/'acceptance.json',acceptance)
    if args.package:
        assert json.loads((out/'browser_acceptance.json').read_text())['state']=='passed'
        package=out.parent/(out.name+'.zip')
        if package.exists():raise ValueError('Do not overwrite dimension package')
        entries=list((out/'assets').iterdir())+[p for p in out.iterdir() if p.is_file() and p.suffix in ('.html','.md','.json','.jsonl','.csv','.jpg','.txt')]
        with ZipFile(package,'w',ZIP_DEFLATED) as z:
            for p in entries:z.write(p,str(p.relative_to(out)))
            z.write(out/'snapshot/manifest.json','evidence/snapshot_manifest.json')
        with ZipFile(package) as z:
            assert z.testzip() is None
            for p in entries:assert hashlib.sha256(z.read(str(p.relative_to(out)))).hexdigest()==digest(p)
        write_json(out/'delivery.json',dict(state='passed',zip=str(package),bytes=package.stat().st_size,sha256=digest(package),members=len(entries)+1,
            offline_entry='index.html',live_database_not_included=True))
    print(json.dumps(acceptance),flush=True)


if __name__=='__main__':main()
