"""Decode L01 once; P02 reuses the verified full-input timestamp map from P01."""
import csv
import hashlib
import json
import os
from pathlib import Path
import av
from part_plan import make_part_plan

root=Path('/eval');part=os.environ['CLIP']
spec=json.loads(Path('/specs.json').read_text())[part]
sha=hashlib.sha256(Path('/source.mp4').read_bytes()).hexdigest()
assert sha==spec['sha256']
if (root/'inputs/sampling_plan.json').exists():
    archived=root/'reports/sampling_plan_attempt01.json'
    assert part=='L01_P02' and archived.is_file()
    assert archived.read_bytes()==(root/'inputs/sampling_plan.json').read_bytes()
    assert not (root/'inputs/pose.json').exists() and not (root/'inputs/pose_candidates_prefilter.jsonl').exists()
    assert not list((root/'inputs/frames').glob('*.png'))
prefix=Path('/prefix_cache')
if part=='L01_P02':
    hashes=json.loads((prefix/'reports/cache_hashes.json').read_text())['files']
    for rel in ('inputs/source_map.csv','inputs/sampling_plan.json','reports/source_probe.json'):
        assert hashlib.sha256((prefix/rel).read_bytes()).hexdigest()==hashes[rel]
    old=json.loads((prefix/'inputs/sampling_plan.json').read_text())
    assert old['source_sha256']==sha and old['part_id']=='L01_P01'
    with (prefix/'inputs/source_map.csv').open() as f:
        mapped=list(csv.DictReader(f))
    assert [int(r['frame_1based']) for r in mapped]==list(range(1,len(mapped)+1))
    pts=[float(r['elapsed_seconds'])+old['source_pts_origin'] for r in mapped]
    meta=json.loads((prefix/'reports/source_probe.json').read_text())
    source_map_reused=True
else:
    pts=[];dimensions=set()
    with av.open('/source.mp4') as source:
        stream=source.streams.video[0];stream.codec_context.thread_count=2
        meta=dict(codec=stream.codec_context.name,width=stream.width,height=stream.height,
                  average_rate=str(stream.average_rate),declared_frames=stream.frames)
        for frame in source.decode(video=0):
            assert frame.pts is not None and not frame.is_corrupt
            pts.append(float(frame.pts*frame.time_base));dimensions.add((frame.width,frame.height))
    assert len(dimensions)==1
    source_map_reused=False
assert len(pts)==19975
if meta['declared_frames']:assert meta['declared_frames']==len(pts)
plan=make_part_plan(pts,spec['display_bounds'],part)
assert len(plan['target_seconds'])==spec['expected_samples']
assert abs(pts[2542]-pts[2541]-1.016668)<1e-6
plan.update(clip=part,source_sha256=sha,decode_errors=0,corrupt_frames=[],source_probe=meta,
            known_loop_boundaries=[],source_map_reused_from_P01=source_map_reused,
            source_frame_semantics='1-based L01 input frame, not part-local or review frame',
            seconds_semantics='actual L01-relative PTS',target_seconds_semantics='part-origin grid on L01 timeline')
with (root/'inputs/source_map.csv').open('w',newline='') as f:
    w=csv.writer(f);w.writerow(['frame_1based','elapsed_seconds']);w.writerows((i+1,p-pts[0]) for i,p in enumerate(pts))
(root/'inputs/sampling_plan.json').write_text(json.dumps(plan,indent=2))
(root/'reports/source_probe.json').write_text(json.dumps(meta,indent=2))
print(json.dumps(dict(part=part,samples=len(plan['target_seconds']),first_selected=plan['source_frame_indices'][0],
                     last_selected=plan['source_frame_indices'][-1],part_origin_seconds=plan['part_origin_seconds'],source_map_reused=source_map_reused)),flush=True)
