"""Independent audit integrity checks and optional compact offline ZIP delivery."""
from contextlib import closing
import argparse
import hashlib
import json
from pathlib import Path
import sqlite3
import sys
import xml.etree.ElementTree as ET
from zipfile import ZipFile,ZIP_DEFLATED

import numpy as np
from PIL import Image

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT))
from pallet.cluster_targets import digest,load_dataset,protected_snapshot
from pallet.data.pcd import read_pcd
from pallet.data.orientation import orient_grid
from pallet.pose_annotation_audit import (DEFAULT,LIVE,canonical,load_geometry,measure_patches,
    read_snapshot,rows,sample_pool,world_ruler,write_json,now)
from pallet.pose_review_geometry import pose_value


def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--package',action='store_true');args=parser.parse_args();out=DEFAULT
    manifest=json.loads((out/'snapshot/manifest.json').read_text());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 name,sha in manifest['protected_inputs'].items():assert digest(PROJECT/name)==sha,name
    protected=json.loads((out/'snapshot/protected_formal.json').read_text());assert protected_snapshot(formal)==protected
    current,histories=read_snapshot(out);classes={r['target_key']:r for r in rows(out/'snapshot/classes.jsonl')};pool=rows(out/'screening.jsonl');samples=rows(out/'samples.jsonl')
    replay,coverage=sample_pool(pool,classes,current)
    assert [r['target_key'] for r in replay]==[r['target_key'] for r in samples]
    assert coverage==json.loads((out/'coverage.json').read_text());assert len(samples)==len({s['target_key'] for s in samples})==191
    assert {s['class_id'] for s in samples}==set(range(1,23))
    cases=[json.loads((out/'cases'/(s['target_key']+'.json')).read_text()) for s in samples]
    references=json.loads((out/'manual_reference_measurements.json').read_text());notes=json.loads((PROJECT/'configs/pallet_pose_annotation_audit_v1_reviews.json').read_text())
    report=json.loads((out/'report_manifest.json').read_text());assert digest(PROJECT/'configs/pallet_pose_annotation_audit_v1_reviews.json')==report['analyst_notes_sha256']
    assert digest(PROJECT/'pallet/pose_annotation_audit.py')==report['audit_code_sha256']
    assert digest(out/'index.html')==report['report_html_sha256']
    selected=rows(out/'selected_reviews.jsonl');assert len(selected)==173
    for r in selected:assert r==current[r['target_key']] and not r['robot_command_eligible']
    selected_history=rows(out/'selected_histories.jsonl')
    for r in selected_history:assert r['events']==histories[r['target_key']]
    frames=set();svg_count=0
    for c in cases:
        s=c['sample'];key=s['target_key'];source=sources[s['frame_id']];frames.add(s['frame_id'])
        assert digest(source['source_paths']['pcd'])==c['evidence']['pcd_sha256']==source['source_anchor_hash']
        assert digest(formal/source['image'])==c['evidence']['image_sha256']
        np.testing.assert_array_equal(np.asarray(Image.open(out/'assets'/(key+'_original.png')).convert('RGB')),
            np.asarray(Image.open(formal/source['image']).convert('RGB')))
        for plane in ('front','top'):
            tree=ET.parse(out/'assets'/(key+'_'+plane+'.svg'));assert tree.getroot().tag.endswith('svg');svg_count+=1
        if not s['eligible']:
            assert c['review'] is None and s['sample_role']=='unannotated_context_no_human_label';continue
        value=current[key];assert c['review']==value
        assert hashlib.sha256(canonical(value)).hexdigest()==s['source_review_sha256']
        meta,data,mask=load_geometry(value,LIVE/'geometry');center,b=world_ruler(value['ruler']);local=(data['xyz'][mask]-center)@b
        np.testing.assert_allclose(local.mean(0),s['point_mean_local_m'],atol=1e-12)
        np.testing.assert_allclose(np.median(local,axis=0),s['point_median_local_m'],atol=1e-12)
        lo,hi=np.quantile(local,[.01,.99],axis=0);assert abs((lo[0]+hi[0])/2-s['visible_quantile_midpoint_local_m'][0])<1e-12
        pose=pose_value(value['ruler'],value['sensor']);assert not pose['robot_command_eligible'] and pose['z'] is None
        if s['case_id'] in references:
            _,native=read_pcd(source['source_paths']['pcd']);w,h=source['size'];mapping=orient_grid(np.arange(w*h).reshape(h,w),source['sensor_policy'])
            check=measure_patches(native,mapping,value['ruler'],value['sensor']['scale_to_m'],notes['boundary_patch_cases'][s['case_id']]['patches'],
                plane_depth=s['point_median_local_m'][1],selected_ids=data['source_indices'][mask])
            assert check['patches']==references[s['case_id']]['patches'] and check['reference']==references[s['case_id']]['reference']
    # The user can keep saving during analysis. Compare immutable old events,
    # not the changing DB file digest or changing latest-row payloads.
    with closing(sqlite3.connect((LIVE/'annotations.sqlite3').resolve().as_uri()+'?mode=ro',uri=True)) as db:
        assert db.execute('PRAGMA quick_check').fetchone()[0]=='ok'
        events={(k,r):raw for k,r,raw in db.execute('SELECT target_key,revision,payload FROM events')}
        latest=dict(db.execute('SELECT target_key,revision FROM annotations'))
    for key,history in histories.items():
        for r in history:assert events[key,r['revision']]==canonical(r).decode()
        assert latest[key]>=current[key]['revision']
    acceptance=dict(state='passed',created_at=now(),source_snapshot_targets=len(current),source_snapshot_events=sum(map(len,histories.values())),
        sample_cases=191,saved_labels=173,unannotated_context_cases=18,classes=22,independent_sampling_replay=True,
        selected_cloud_statistics_recomputed=173,edge_patch_cases_recomputed=len(references),valid_SVGs=svg_count,
        unique_source_frames_rehashed=len(frames),protected_formal_files_unchanged=len(protected),
        historical_live_events_preserved=sum(map(len,histories.values())),additional_live_events_observed=len(events)-sum(map(len,histories.values())),
        original_labels_raw_PCDs_and_old_model_deliveries_unchanged=True,source_annotation_writes=0,
        offline_report_no_model_reselection=True,physical_center_GT_or_robot_eligibility_generated=False)
    write_json(out/'acceptance.json',acceptance)
    if args.package:
        browser=json.loads((out/'browser_acceptance.json').read_text());assert browser['state']=='passed'
        package=out.parent/(out.name+'.zip')
        if package.exists():raise ValueError('Do not overwrite an existing audit delivery')
        entries=[p for folder in ('assets','cases','contact_sheets') for p in (out/folder).iterdir() if p.is_file()]
        entries+=[out/name for name in ('index.html','REPORT_zh.md','annotation_guidelines_zh.md','sample_review_queue.csv','selected_reviews.jsonl',
            'selected_histories.jsonl','coverage.json','findings.json','manual_reference_measurements.json','sampling_policy.json','report_manifest.json',
            'acceptance.json','browser_acceptance.json','FONT_LICENSE.txt')]
        tmp=package.with_suffix('.tmp')
        with ZipFile(tmp,'w',ZIP_DEFLATED,compresslevel=6) as z:
            for path in sorted(entries):z.write(path,str(path.relative_to(out)))
            z.write(out/'snapshot/manifest.json','evidence/snapshot_manifest.json')
        tmp.replace(package)
        with ZipFile(package) as z:
            assert z.testzip() is None
            for path in entries:assert hashlib.sha256(z.read(str(path.relative_to(out)))).hexdigest()==digest(path)
        write_json(out/'delivery.json',dict(state='passed',zip=str(package),bytes=package.stat().st_size,sha256=digest(package),
            members=len(entries)+1,source_database_not_in_delivery=True,raw_source_PCD_not_in_delivery=True,
            all_selected_saved_reviews_and_histories_included=True,offline_unpack_and_open='index.html'))
    print(json.dumps(acceptance,ensure_ascii=False),flush=True)


if __name__=='__main__':main()
