"""Publish the already encoded pilot after EXDEV, without inference or re-encoding."""
import csv
import hashlib
import json
import os
import pathlib
import shutil
import av
from contract import palette

clip=os.environ['CLIP'];assert clip=='02_camera22_crowd'
root=pathlib.Path('/eval');cache=pathlib.Path('/cache');dest=pathlib.Path('/download')/clip;data=dest/'data'
draft=root/'reports/render-b6cd2245e0bd44778e62901904305c60.mp4';out=dest/'Pose_Input_Review.mp4'
assert draft.is_file() and not out.exists()
check=json.loads((root/'reports/cache_validation.json').read_text())
all_rows=json.loads((cache/'inputs/pose.json').read_text());rows=[all_rows[i] for i in check['selected_samples']]
facts=[json.loads(line) for line in (data/'observation_states.jsonl').read_text().splitlines()]
assert len(rows)==len(facts)==201
with av.open(str(draft)) as movie:
    movie.streams.video[0].codec_context.thread_count=2
    times=[]
    for frame in movie.decode(video=0):
        assert not frame.is_corrupt and (frame.width,frame.height)==(3200,1800)
        times.append(float(frame.pts*frame.time_base))
mapping=[];rgb={};maximum=omitted=far=0
for i,(r,fact) in enumerate(zip(rows,facts)):
    assert (r['sample'],r['source_frame'],r['seconds'])==(fact['sample'],fact['source_frame'],fact['seconds'])
    shown=sum(p['visible'] for p in fact['persons']);maximum=max(maximum,shown);omitted=max(omitted,max(0,shown-3));far+=fact['labels']['far_labels']
    mapping.append(dict(output_frame=i+1,sample=r['sample'],source_frame=r['source_frame'],source_seconds=r['seconds'],
        output_pts_seconds=round((r['seconds']-rows[0]['seconds'])*90000)/90000,visible=shown,detail=min(3,shown),omitted=max(0,shown-3)))
    path=cache/'inputs/frames'/f"{r['sample']:04d}.png";rgb[path.name]=hashlib.sha256(path.read_bytes()).hexdigest()
assert len(times)==201
error=max(abs(t-m['output_pts_seconds']) for t,m in zip(times,mapping));assert error<1/90000
digest=hashlib.sha256(draft.read_bytes()).hexdigest();shutil.copyfile(draft,out);assert hashlib.sha256(out.read_bytes()).hexdigest()==digest
with (data/'frame_map.csv').open('w',newline='') as f:
    writer=csv.DictWriter(f,fieldnames=mapping[0]);writer.writeheader();writer.writerows(mapping)
(data/'input_rgb_sha256.json').write_text(json.dumps(rgb,indent=2))
(data/'cache_validation.json').write_text(json.dumps(check,indent=2))
(data/'pose_summary.json').write_bytes((cache/'reports/pose_summary.json').read_bytes())
(data/'identity_palette.json').write_text(json.dumps(palette(rows),indent=2))
report=dict(status='PASS',clip=clip,frames=201,first_source_frame=rows[0]['source_frame'],last_source_frame=rows[-1]['source_frame'],
    first_seconds=rows[0]['seconds'],last_seconds=rows[-1]['seconds'],nominal_fps=10,resolution=[3200,1800],max_pts_error=error,
    all_frame_text_overflow=0,all_frame_text_overlap=0,label_overlap=0,label_joint_edge_overlap=0,
    max_visible=maximum,max_detail_omitted=omitted,relocated_labels=far,
    sample_indices=sorted(int(p.stem.split('_')[1]) for p in data.glob('sample_*.jpg')),
    source_sha256=check['source_sha256'],cache_sha256=check['cache_sha256'],sha256=digest,
    elapsed_seconds=None,cpu_only=True,engine_or_model_decision=False,
    publish_recovery='EXDEV after full rendering, text assertions and decoding; original encoded bytes copied and hash-verified; no re-encoding')
(data/'video_validation.json').write_text(json.dumps(report,indent=2));print(json.dumps(report),flush=True)
