"""Seal completed review outputs; never package credentials or heavy source caches."""
import csv
import hashlib
import json
from pathlib import Path
import shutil
from inputs import OUT


def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()


dest=OUT/'download';validation=dest/'validation'
manifest=json.loads((OUT/'candidates.json').read_text());representatives=manifest['representative_clips']
videos=[]
for clip in representatives:
    maps=list(csv.DictReader((dest/clip/'data/frame_map.csv').open()))
    for candidate in manifest['candidates']:
        cid=candidate['id'];path=dest/clip/(cid+'_Review.mp4')
        result=json.loads((dest/clip/'data'/(cid+'_video_validation.json')).read_text())
        assert result['status']=='PASS' and result['frames']==len(maps) and result['sha256']==sha(path)
        videos.append(dict(clip=clip,candidate=cid,path=str(path.relative_to(dest)),frames=result['frames'],
            first_source_frame=maps[0]['source_frame'],last_source_frame=maps[-1]['source_frame'],sha256=result['sha256']))
assert len(videos)==18 and len(list(dest.glob('*/*.mp4')))==18
with (dest/'video_list.csv').open('w',newline='',encoding='utf-8-sig') as f:
    w=csv.DictWriter(f,fieldnames=videos[0]);w.writeheader();w.writerows(videos)
shutil.copy2(OUT/'00_README_ko.txt',dest/'00_README_ko.txt')
code=validation/'implementation';code.mkdir(exist_ok=True)
code_hashes={}
for name in ('geometry.py','motion.py','decision.py','seed_follow.py','inputs.py','extract_features.py','evaluate.py','test_core.py','audit_results.py','render_candidates.py','search_candidates.py','search_seed_follow.py'):
    p=OUT/'helpers'/name;shutil.copy2(p,code/name);code_hashes[name]=sha(p)
(validation/'helper_sha256.json').write_text(json.dumps(code_hashes,indent=2))
for name in ('production_before.json','production_after.json','operational_comparison.json','technical_sample_review.json','unit_tests_final.log'):
    assert (OUT/'reports'/name).exists(),name
    shutil.copy2(OUT/'reports'/name,validation/name)
resources={p.name:json.loads(p.read_text()) for p in (OUT/'reports').glob('*_resources.json')}
(validation/'resource_samples.json').write_text(json.dumps(resources,ensure_ascii=False,indent=2))
summary=dict(status='PASS',clips_with_diagnostics=37,representative_inputs=9,videos=len(videos),
    output_frames=sum(v['frames'] for v in videos),all_decoded=True,source_pts_preserved=True,
    no_model_or_pose_tracking_execution=True,hashes_cover_all_deliverables=True)
(validation/'package_validation.json').write_text(json.dumps(summary,indent=2))
entries=[]
for p in sorted(dest.rglob('*')):
    if not p.is_file() or p.name=='SHA256SUMS.txt':continue
    assert not p.is_symlink() and p.suffix not in ('.engine','.pth','.onnx')
    if p.suffix in ('.json','.jsonl','.csv','.txt','.md','.py','.log'):
        raw=p.read_bytes()
        for forbidden in (b'BEGIN OPENSSH PRIVATE KEY',b'sudo.password',b'58.233.207.31',b'rtsp://',b'Authorization: Bearer'):
            assert forbidden not in raw,(p.name,'sensitive routing or credential text')
    entries.append(sha(p)+'  '+str(p.relative_to(dest)))
(dest/'SHA256SUMS.txt').write_text('\n'.join(entries)+'\n')
print(json.dumps(dict(summary,files=len(entries),bytes=sum(p.stat().st_size for p in dest.rglob('*') if p.is_file())),ensure_ascii=False),flush=True)
