"""Read-only source audit; write new evidence only under benchmark v3."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import sqlite3
import subprocess
import sys

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_benchmark import ROOT, SOURCE, read_rows, atomic_json


def main():
    formal=Path(json.loads((PROJECT/'configs/active_formal_dataset.json').read_text())['dataset'])
    annotations,sources=load_dataset(formal)
    assert protected_snapshot(formal)==json.loads((SOURCE/'snapshot/protected_formal.json').read_text())
    def check(source):
        assert digest(source['source_paths']['pcd'])==source['source_anchor_hash']
        assert digest(formal/source['image'])==source['files'][source['image']]
    with ThreadPoolExecutor(max_workers=8) as pool:list(pool.map(check,sources.values()))
    dbpath=(PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3').resolve()
    with sqlite3.connect(dbpath.as_uri()+'?mode=ro',uri=True) as db:
        assert db.execute('PRAGMA quick_check').fetchone()[0]=='ok'
        events={(k,r):hashlib.sha256(p.encode()).hexdigest() for k,r,p in db.execute('SELECT target_key,revision,payload FROM events')}
        live={k:r for k,r in db.execute('SELECT target_key,revision FROM annotations')}
    original=read_rows(SOURCE/'snapshot/event_fingerprints.jsonl')
    for e in original:assert events[(e['target_key'],e['revision'])]==e['payload_sha256']
    snapshot=json.loads((SOURCE/'snapshot/manifest.json').read_text())
    assert set(snapshot['all_saved_keys'])<=set(live)
    for row in json.loads((ROOT/'upstream_manifest.json').read_text()):
        p=Path(row['path']);assert subprocess.check_output(['git','rev-parse','HEAD'],cwd=p,text=True).strip()==row['commit']
        assert not subprocess.check_output(['git','diff','--name-only'],cwd=p,text=True).strip()
    identity=[]
    weights=json.loads((ROOT/'weights_manifest.json').read_text())
    for row in weights:
        assert digest(ROOT/'weights'/row['name'])==row['sha256']
        name={'utonia_small.pth':'utonia','concerto_small.pth':'concerto','sonata.pth':'sonata','litept_scan.pth':'litept'}.get(row['name'])
        if name:
            metadata=json.loads((ROOT/(name+'_weight_identity.json')).read_text())[0]
            assert metadata['lfs']['oid']==row['sha256']
            identity.append(dict(name=row['name'],published_LFS_hash_matches=True))
    old_paths=['configs/active_pose_annotations.json','configs/active_pose_refinement.json',
               'outputs/pallet_pose_refinement_v2/pallet_pose_annotations_v2.zip',
               'outputs/pallet_pose_refinement_v2/pallet_pose_refined_models_v2.zip']
    audit=dict(state='passed',source_frames_rehashed=len(sources),protected_files_unchanged=len(protected_snapshot(formal)),
               original_human_targets_preserved=len(snapshot['all_saved_keys']),original_events_preserved=len(original),
               current_human_targets=len(live),current_events=len(events),published_weight_identity=identity,
               old_entries_and_packages={p:digest(PROJECT/p) for p in old_paths},writes_to_source_database=0)
    atomic_json(ROOT/'integrity_audit.json',audit);print(json.dumps(audit),flush=True)


if __name__=='__main__':main()
