"""Finalize evidence only: residual diagnostics, source hashes, transfer manifest."""
import json,sys,shutil
from pathlib import Path
sys.path.insert(0,'/evidence/2026-11-01_contextra-fall-spatial-28clips_r01/helpers')
from common import OUT,read,save,sha,evidence

package=OUT/'download';specs=read(OUT/'specs.json');clip='15_KISA_fall_C00_096_0008'
old=[json.loads(l) for l in evidence(specs[clip]['r1_trace']).open()]
new=[json.loads(l) for l in (package/clip/'data/R2_diagnostics.jsonl').open()]
residual=[]
for a,b in zip(old,new):
 if not a['displayed'] or not a['baseline']['matched_scores']['current_hit'] or a['candidate']['hit']:continue
 residual.append(dict(source_frame=b['source_frame'],seconds=b['seconds'],recovered=b['r2']['hit'],
  standing_support=any('LOCAL_STANDING_SUPPORT' in p['reasons'] for p in a['people']),
  r1_people=b['people'],extra=b['extra'],additional=b['additional']))
save(package/'residual_15.json',residual)
for name in ('00_README_ko.md','checkpoint.ko.md','DESIGN.ko.md'):shutil.copyfile(OUT/name,package/name)
shutil.copyfile(OUT/'helpers/seal_depth.py',package/'helpers/seal_depth.py')
assert all(sha(OUT/name)==value for name,value in read(package/'validation/source_fingerprints.json').items())
save(package/'validation/final_source_fingerprints.json',{str(p.relative_to(OUT)):sha(p) for p in sorted((OUT/'helpers').glob('*.py'))})
summaries=[read(package/c/'data/summary.json') for c in specs]
save(package/'validation/cpu_processing.json',dict(sum_input_evaluation_seconds=sum(s['elapsed_seconds'] for s in summaries),
 per_input=[dict(clip=s['clip'],seconds=s['elapsed_seconds'],full_observations=s['input_observations']) for s in summaries],
 scope='CPU rules + JSON I/O only; excludes model/Tracking/render/transfer; no live FPS claim',
 cap=dict(cpus=2,memory_gib=8,max_parallel=2,actual_parallel=1,timeout_seconds=1800),
 resource_samples='Jobs ended before the 30-second sampler; no actual per-job peak CPU/RAM claim'))
files={str(p.relative_to(package)):sha(p) for p in sorted(package.rglob('*')) if p.is_file()}
assert not any(p.endswith(('.mp4','.avi','.onnx','.pt','.engine')) for p in files)
save(package/'validation/transfer_sha256.json',dict(algorithm='SHA256',files=files,count=len(files),self_excluded=True))
print(json.dumps(dict(status='PASS',files=len(files),candidate_sha256=sha(OUT/'conditions.json'),remaining_15_support=sum(x['standing_support'] and not x['recovered'] for x in residual))))
