#!/usr/bin/env python3
"""Render a local comparison body from a freshly validated repair request.

Never applies changes to the project selection. Delivery titles and captions
remain a separate, evidenced composition step. No provider is invoked.
"""
from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
import subprocess
import tempfile

from repair_plan import bound_file, build_plan, canonical, digest, video_info


def audio_hash(path):
    packets = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a",
        "-show_streams", "-show_packets", "-show_entries",
        "stream=codec_name,time_base,start_pts:packet=pts,dts,duration,size,flags", "-of", "json", str(path)],
        capture_output=True, text=True, timeout=120, check=True)
    timeline = json.loads(packets.stdout)
    if not timeline.get("streams"):
        return None
    result = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-map", "0:a?",
        "-c", "copy", "-f", "streamhash", "-hash", "sha256", "-"],
        capture_output=True, text=True, timeout=120, check=True)
    # Audio-only outputs use stable stream numbering, independent of the input layout.
    return {"payload": result.stdout.strip(), "packetTimeline": timeline}


def render(request_path, out_dir):
    root = request_path.resolve().parent
    request = json.loads(request_path.read_text())
    plan = build_plan(request, root)
    if not plan["edits"]:
        raise ValueError("no eligible picture edits to preview")
    out_dir = out_dir.resolve()
    out_dir.mkdir(parents=True, exist_ok=True)
    stem = "repair-" + plan["requestSha256"][:16]
    output = out_dir / (stem + ".mp4")
    report = out_dir / (stem + ".json")
    protected = {request_path.resolve()}
    records = [request["master"], request["selection"], *[r["source"] for r in request.get("ranges", [])]]
    protected.update(bound_file(record, root) for record in records)
    if output in protected or report in protected:
        raise ValueError("preview output would overwrite an input")
    if output.exists() or report.exists():
        if output.exists() and report.exists():
            prior = json.loads(report.read_text())
            if prior.get("plan") == plan and prior.get("outputSha256") == digest(output):
                return report
        raise ValueError("existing preview is incomplete or changed; use a new output directory")
    master = bound_file(request["master"], root)
    probe = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_entries", "stream=width,height,sample_aspect_ratio,start_pts", "-of", "json", str(master)],
        capture_output=True, text=True, check=True, timeout=60)
    stream = json.loads(probe.stdout)["streams"][0]
    width, height = stream["width"], stream["height"]
    if stream.get("start_pts") != 0:
        raise ValueError("preview requires a body whose picture starts at timestamp zero")
    if stream.get("sample_aspect_ratio", "1:1") not in ("1:1", "N/A"):
        raise ValueError("normalise non-square master pixels before previewing")
    edits = sorted(plan["edits"], key=lambda e: e["startFrame"])
    pieces = sorted([dict(p, kind="original") for p in plan["untouched"]] +
                    [dict(p, kind="edit") for p in edits], key=lambda p: p["startFrame"])
    inputs = ["-i", str(master)]
    filters, labels = [], []
    next_input = 1
    for index, piece in enumerate(pieces):
        label = f"v{index}"
        if piece["kind"] == "original":
            chain = f"[0:v]trim=start_frame={piece['startFrame']}:end_frame={piece['endFrame']},setpts=PTS-STARTPTS"
        else:
            inputs.extend(["-i", str(bound_file(piece["source"], root))])
            chain = (f"[{next_input}:v]trim=start_frame={piece['sourceInFrame']}:end_frame={piece['sourceOutFrameExclusive']},"
                     f"setpts=PTS-STARTPTS,fps=fps={plan['fps']}:eof_action=pass,"
                     f"trim=end_frame={piece['outputFrames']},setpts=PTS-STARTPTS,"
                     f"scale={width}:{height}:force_original_aspect_ratio=decrease,"
                     f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1")
            next_input += 1
        filters.append(chain + f",format=yuv420p[{label}]")
        labels.append(f"[{label}]")
    filters.append("".join(labels) + f"concat=n={len(pieces)}:v=1:a=0[outv]")
    original_audio = audio_hash(master)
    with tempfile.TemporaryDirectory(prefix="repair-preview-", dir=out_dir) as temp:
        candidate = Path(temp) / "candidate.mp4"
        # The graph goes inline: ffmpeg 8 removed -filter_complex_script (deprecated in 7.0
        # for `-/filter_complex <file>`, which ffmpeg 6 on CI does not know). Inline is the
        # one spelling every supported ffmpeg accepts.
        graph = ";".join(filters)
        subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-filter_complex_threads", "2", *inputs,
            "-filter_complex", graph, "-map", "[outv]", "-map", "0:a?",
            "-c:v", "libx264", "-preset", "fast", "-crf", "16", "-threads", "2",
            "-fps_mode", "passthrough", "-c:a", "copy", "-map_metadata", "0", "-movflags", "+faststart",
            str(candidate)], check=True)
        if video_info(candidate) != video_info(master):
            raise ValueError("preview changed frame count/rate; not published")
        if audio_hash(candidate) != original_audio:
            raise ValueError("preview changed audio payload; not published")
        if canonical(json.loads(request_path.read_text())) != canonical(request):
            raise ValueError("request changed during render; not published")
        if canonical(build_plan(request, root)) != canonical(plan):
            raise ValueError("request/source evidence changed during render; not published")
        result = {"plan": plan, "output": str(output), "outputSha256": digest(candidate),
            "audioPayloadUnchanged": True, "audioPacketClocksUnchanged": True, "frameCountAndRateUnchanged": True,
            "reviewRequired": True, "deliveryReady": False,
            "limitations": ["Local body comparison only; inspect motion, returns and visible performance.",
                "Title/caption delivery composition and continuous audiovisual review remain required."]}
        # Exclusive publication protects work arriving during a long encode.
        # A report collision leaves a clearly incomplete preview; never overwrite
        # or remove a path another run may own.
        os.link(candidate, output)
        with report.open("x") as stream:
            stream.write(json.dumps(result, indent=2) + "\n")
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--request", required=True, type=Path)
    parser.add_argument("--out-dir", required=True, type=Path)
    args = parser.parse_args()
    try:
        print(json.dumps({"report": str(render(args.request, args.out_dir))}))
    except (ValueError, KeyError, TypeError, OSError, subprocess.SubprocessError) as exc:
        parser.error(str(exc))


if __name__ == "__main__":
    main()
