"""Assemble one cut from a shot table. Template for the curriculum (Chapter 1).

Usage:  python3 build_cut.py <shots.csv> <cut_name>

shots.csv columns:  name, source, start, duration [, audio, audio_offset]
  name          short label for the shot (no spaces)
  source        path to a clip OR a still image (.png/.jpg), relative to the csv;
                a still is held for the whole duration (animatic, Chapter 10)
  start         seconds into the source where the shot begins (ignored for a still)
  duration      seconds to keep
  audio         optional: a sound file laid over this shot (a recorded line), relative to the csv
  audio_offset  optional: seconds after the shot's start where that file begins (default 0)
  When `audio` is given it replaces the source's own sound for this shot. One file per shot;
  a line that must run across a cut (a J or L cut) belongs to the mix stage (Chapter 14).

Output goes to a NEW folder <cut_name>/ next to the csv. If the folder already
holds an export the script stops: a cut is never overwritten, a change is a new cut.
Writes manifest.json (what was planned) and verification.json (what was measured).
"""
import csv, json, subprocess, sys
from pathlib import Path

FPS, W, H = 24, 1280, 720


def run(args):
    p = subprocess.run(args, capture_output=True, text=True)
    if p.returncode:
        raise SystemExit(f"FAILED: {' '.join(args[:4])} ...\n{p.stderr[-2000:]}")
    return p.stdout


def probe(path):
    return json.loads(run(['ffprobe', '-v', 'error', '-show_streams', '-show_format', '-of', 'json', str(path)]))


def video_frames(path):
    # Count by decoding: nb_frames is missing in some containers (webm, some mkv).
    out = run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-count_frames',
               '-show_entries', 'stream=nb_read_frames', '-of', 'csv=p=0', str(path)]).strip()
    if not out.isdigit():
        raise SystemExit(f'could not count frames in {path}: ffprobe returned {out!r}')
    return int(out)


def main():
    table, cut = Path(sys.argv[1]).resolve(), sys.argv[2]
    out = table.parent / cut
    export = out / f'{cut}.mp4'
    if export.exists():
        raise SystemExit(f'{export} exists. A cut is never overwritten; pick a new cut name.')
    (out / 'segments').mkdir(parents=True, exist_ok=True)

    items, cursor = [], 0.0
    for n, row in enumerate(csv.DictReader(table.open())):
        dur = round(float(row['duration']) * FPS) / FPS  # whole frames only
        src = (table.parent / row['source']).resolve()
        if not src.exists():
            raise SystemExit(f"missing source for {row['name']}: {src}")
        audio = (row.get('audio') or '').strip()
        if audio:
            audio = str((table.parent / audio).resolve())
            if not Path(audio).exists():
                raise SystemExit(f"missing audio for {row['name']}: {audio}")
        items.append(dict(name=row['name'], source=str(src), start=float(row['start'] or 0), duration=dur,
                          frames=round(dur * FPS), timeline_start=cursor,
                          audio=audio, audio_offset=float(row.get('audio_offset') or 0),
                          segment=str(out / 'segments' / f"{n:02d}_{row['name']}.mov")))
        cursor += dur
    (out / 'manifest.json').write_text(json.dumps(dict(cut=cut, fps=FPS, planned_duration=cursor, items=items), indent=2) + '\n')

    for x in items:
        still = Path(x['source']).suffix.lower() in ('.png', '.jpg', '.jpeg')
        if still:
            args = ['ffmpeg', '-v', 'error', '-n', '-loop', '1', '-framerate', str(FPS), '-i', x['source']]
            has_audio = False
        else:
            has_audio = any(s['codec_type'] == 'audio' for s in probe(x['source'])['streams'])
            args = ['ffmpeg', '-v', 'error', '-n', '-ss', str(x['start']), '-i', x['source']]
        # One-frame fade at both ends so hard joins do not click. Dialogue placement is a later chapter.
        fade = f"afade=t=in:d={1/FPS:.5f},afade=t=out:st={x['duration'] - 1/FPS:.5f}:d={1/FPS:.5f}"
        if x['audio']:  # a recorded line laid over the shot, replacing the source's own sound
            args += ['-i', x['audio']]
            afilter = (f"[1:a]adelay={int(x['audio_offset'] * 1000)}:all=1,apad,aresample=48000,"
                       f"aformat=channel_layouts=stereo,{fade}[a]")
        elif has_audio:
            afilter = f'[0:a]apad,aresample=48000,aformat=channel_layouts=stereo,{fade}[a]'
        else:  # silent: give it a silent track so every segment has the same shape
            args += ['-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=stereo']
            afilter = '[1:a]anull[a]'
        args += ['-filter_complex', f'[0:v]fps={FPS},scale={W}:{H},setsar=1,format=yuv420p[v];{afilter}',
                 '-map', '[v]', '-map', '[a]', '-t', str(x['duration']),
                 '-c:v', 'libx264', '-crf', '18', '-video_track_timescale', '24000', '-c:a', 'pcm_s16le', x['segment']]
        run(args)
        got = video_frames(x['segment'])
        if got != x['frames']:
            raise SystemExit(f"{x['name']}: expected {x['frames']} frames, got {got}")

    concat = out / 'concat.txt'
    concat.write_text(''.join(f"file '{x['segment']}'\n" for x in items))
    run(['ffmpeg', '-v', 'error', '-n', '-f', 'concat', '-safe', '0', '-i', str(concat),
         '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', str(export)])

    run(['ffmpeg', '-v', 'error', '-i', str(export), '-f', 'null', '-'])  # full decode: every frame read once
    expected, actual = sum(x['frames'] for x in items), video_frames(export)
    (out / 'verification.json').write_text(json.dumps(dict(
        full_decode='exit0', expected_frames=expected, actual_frames=actual,
        duration=probe(export)['format']['duration'],
        status='Technical decode only. Not a quality approval.'), indent=2) + '\n')
    if expected != actual:
        raise SystemExit(f'frame count mismatch: expected {expected}, got {actual}')
    print(f'OK {export}  {actual} frames  {actual / FPS:.3f} s')


if __name__ == '__main__':
    main()
