#!/usr/bin/env python3
"""Propose frame-exact, reuse-first picture repairs from reviewed source ranges.

This command does not render, upload, generate, or change the selection. Inputs
must identify the exact master/selection and carry independent visual evidence.
"""
from __future__ import annotations

import argparse
import hashlib
import json
from fractions import Fraction
from pathlib import Path
import subprocess


def digest(path):
    with Path(path).open("rb") as stream:
        return hashlib.file_digest(stream, "sha256").hexdigest()


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False)


def integer(value, name, minimum=0):
    if type(value) is not int or value < minimum:
        raise ValueError(f"{name} must be an integer >= {minimum}")
    return value


def rate(value):
    try:
        result = Fraction(str(value))
    except (ValueError, ZeroDivisionError) as exc:
        raise ValueError("invalid frame rate") from exc
    if result <= 0 or result > 240:
        raise ValueError("frame rate must be in (0, 240]")
    return result


def bound_file(record, root):
    path = Path(record["path"])
    if not path.is_absolute():
        path = root / path
    path = path.resolve()
    if digest(path) != record["sha256"]:
        raise ValueError(f"stale file hash: {path}")
    return path


def video_info(path, evidence=None):
    run = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_entries", "stream=avg_frame_rate,r_frame_rate,nb_frames,duration_ts,time_base",
        "-of", "json", str(path)], capture_output=True, text=True, timeout=60, check=True)
    streams = json.loads(run.stdout).get("streams", [])
    if not streams:
        raise ValueError(f"no picture stream: {path}")
    stream = streams[0]
    fps = rate(stream["r_frame_rate"])
    frames = int(stream.get("nb_frames", 0))
    if frames <= 0:
        raise ValueError(f"explicit source frame count required: {path}")
    # Rounded final sample duration can distort avg_frame_rate on genuinely CFR
    # masters. Verify presentation timestamps against the rational grid instead.
    # Concatenated masters can accumulate sub-millisecond sample rounding; bound
    # and report this explicitly, never accepting a substantial frame drift.
    packets = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_packets", "-show_entries", "packet=pts", "-of", "json", str(path)],
        capture_output=True, text=True, timeout=60, check=True)
    rows = json.loads(packets.stdout).get("packets", [])
    if len(rows) != frames or any(type(row.get("pts")) is not int for row in rows):
        raise ValueError(f"frame packet timestamps incomplete: {path}")
    times = sorted(row["pts"] for row in rows)
    tick = Fraction(stream["time_base"])
    if tick <= 0 or tick * fps > Fraction(1, 2) or len(set(times)) != frames:
        raise ValueError(f"ambiguous frame timestamp grid: {path}")
    tolerance = min(Fraction(1, 1000), Fraction(1, 40) / fps)
    deviation = max(abs((stamp - times[0]) * tick - Fraction(index, 1) / fps)
                    for index, stamp in enumerate(times))
    if deviation > tolerance:
        raise ValueError(f"variable frame timestamps need normalisation: {path}")
    if evidence is not None:
        evidence.update(nominalFps=str(fps), frames=frames, maxGridDeviationSeconds=str(deviation),
                        allowedGridDeviationSeconds=str(tolerance), packetGridChecked=True)
    return fps, frames


def overlaps(a, b):
    return a[0] < b[1] and b[0] < a[1]


def build_plan(request, root=Path(".")):
    if request.get("schemaVersion") != 1 or request.get("clock") != "body-frames":
        raise ValueError("schemaVersion 1 and body-frames clock required")
    fps = rate(request["fps"])
    total = integer(request["totalFrames"], "totalFrames", 1)
    minimum = integer(request.get("minimumPieceFrames", 12), "minimumPieceFrames", 1)
    master = bound_file(request["master"], root)
    bound_file(request["selection"], root)
    master_clock = {}
    if video_info(master, master_clock) != (fps, total):
        raise ValueError("master frame count/rate differs from request")
    defects = sorted(request["defects"], key=lambda d: (d["startFrame"], d["id"]))
    ids = set()
    active_intervals = []
    for defect in defects:
        if not isinstance(defect["id"], str) or not defect["id"] or defect["id"] in ids:
            raise ValueError("defect IDs must be unique nonempty strings")
        ids.add(defect["id"])
        start = integer(defect["startFrame"], "defect startFrame")
        end = integer(defect["endFrame"], "defect endFrame", 1)
        if not start < end <= total:
            raise ValueError("defect lies outside master")
        if defect["status"] not in ("confirmed", "suspected", "unreviewed", "retired"):
            raise ValueError("invalid defect status")
        if defect["status"] == "confirmed":
            if any(overlaps((start, end), item) for item in active_intervals):
                raise ValueError("confirmed defects overlap; consolidate intervals first")
            active_intervals.append((start, end))
    ranges = sorted(request.get("ranges", []), key=lambda r: r["id"])
    if len({r["id"] for r in ranges}) != len(ranges):
        raise ValueError("source range IDs must be unique")
    verified = {}
    source_clocks = []
    prior_uses = {}
    for item in ranges:
        source = bound_file(item["source"], root)
        key = (str(source), item["source"]["sha256"])
        if key not in verified:
            clock = {"path": str(source), "sha256": item["source"]["sha256"]}
            verified[key] = video_info(source, clock)
            source_clocks.append(clock)
        source_fps, source_frames = verified[key]
        start = integer(item["inFrame"], "source inFrame")
        end = integer(item["outFrame"], "source outFrame", 1)
        if not start < end <= source_frames:
            raise ValueError(f"source range out of bounds: {item['id']}")
        if rate(item["fps"]) != source_fps:
            raise ValueError(f"source rate mismatch: {item['id']}")
        for use in item.get("priorUses", []):
            a = integer(use["inFrame"], "prior use inFrame")
            b = integer(use["outFrame"], "prior use outFrame", 1)
            if not a < b <= source_frames:
                raise ValueError("prior use out of bounds")
            timeline = None
            if "timelineStartFrame" in use or "timelineEndFrame" in use:
                ta = integer(use["timelineStartFrame"], "prior timeline start")
                tb = integer(use["timelineEndFrame"], "prior timeline end", 1)
                if not ta < tb <= total:
                    raise ValueError("prior timeline use out of bounds")
                timeline = (ta, tb)
            prior_uses.setdefault(item["source"]["sha256"], []).append((a, b, timeline))
    edits, gaps, reviews, options, used = [], [], [], [], {}
    for defect in defects:
        if defect["status"] == "retired":
            continue
        if defect["status"] != "confirmed" or not defect.get("evidence"):
            reviews.append({"defectId": defect["id"], "action": "verify-defect", "reason": "No confirmed evidenced defect; retain current picture."})
            continue
        cursor, end = defect["startFrame"], defect["endFrame"]
        eligible = []
        for item in ranges:
            reason = None
            capacity = int(Fraction(item["outFrame"] - item["inFrame"]) * fps / rate(item["fps"]))
            conflicting_uses = [u for u in prior_uses.get(item["source"]["sha256"], [])
                if overlaps((item["inFrame"], item["outFrame"]), u[:2])
                and not (u[2] is not None and defect["startFrame"] <= u[2][0]
                    and u[2][1] <= end and capacity >= end - defect["startFrame"])]
            if defect["id"] not in item.get("targetDefectIds", []):
                reason = "range not reviewed for this defect"
            elif item.get("role") != "cutaway":
                reason = "performance/timing repair requires separate independent verification"
            elif item.get("reviewed") is not True or not item.get("evidence"):
                reason = "visual review evidence missing"
            elif item.get("knownDefects"):
                reason = "source range has unresolved defects"
            elif not defect.get("setting") or item.get("setting") != defect["setting"]:
                reason = "visual setting not matched"
            elif conflicting_uses:
                reason = "range already used; review repetition explicitly"
            elif any(overlaps((item["inFrame"], item["outFrame"]), u) for u in used.get(item["source"]["sha256"], [])):
                reason = "range already allocated in this plan"
            capacity = int(Fraction(item["outFrame"] - item["inFrame"]) * fps / rate(item["fps"]))
            if reason is None and capacity < minimum:
                reason = "reviewed range too short for minimum shot length"
            option = {"defectId": defect["id"], "rangeId": item["id"], "status": "rejected" if reason else "eligible", "reason": reason}
            options.append(option)
            if reason is None:
                eligible.append((item, capacity, option))
        # Prefer fewer cuts; deterministic ID order breaks equal-capacity ties.
        eligible.sort(key=lambda row: (-row[1], row[0]["id"]))
        for index, (item, capacity, option) in enumerate(eligible):
            if cursor == end:
                break
            key = item["source"]["sha256"]
            if any(overlaps((item["inFrame"], item["outFrame"]), u) for u in used.get(key, [])):
                option.update(status="rejected", reason="overlapping source alias already allocated")
                continue
            take = min(capacity, end - cursor)
            tail = end - cursor - take
            if 0 < tail < minimum and index + 1 < len(eligible):
                take -= minimum - tail
            if take < minimum:
                continue
            source_end = Fraction(item["inFrame"]) + Fraction(take) * rate(item["fps"]) / fps
            used_end = -(-source_end.numerator // source_end.denominator)
            edits.append({"defectId": defect["id"], "rangeId": item["id"], "startFrame": cursor,
                "endFrame": cursor + take, "source": item["source"], "sourceInFrame": item["inFrame"],
                "sourceOutFrameExclusive": used_end, "sourceFps": str(rate(item["fps"])),
                "outputFrames": take, "audio": "preserve-master", "speed": 1,
                "reviewRequired": True, "evidence": item["evidence"],
                "cautions": item.get("cautions", []), "defectProperty": defect.get("property"),
                "reason": defect.get("reason"), "evidenceQualification": defect.get("evidenceQualification")})
            used.setdefault(key, []).append((item["inFrame"], used_end))
            option.update(status="selected", reason="reviewed owned range with sufficient moving picture")
            cursor += take
        if cursor < end:
            complete = request.get("inventoryComplete") is True and bool(request.get("inventoryEvidence"))
            gaps.append({"defectId": defect["id"], "startFrame": cursor, "endFrame": end,
                "action": "review-new-footage-proposal" if complete else "review-owned-ranges",
                "reason": "No eligible reviewed range covers this gap; no provider job authorised or submitted."})
    untouched, cursor = [], 0
    for edit in sorted(edits, key=lambda e: e["startFrame"]):
        if cursor < edit["startFrame"]:
            untouched.append({"startFrame": cursor, "endFrame": edit["startFrame"]})
        cursor = edit["endFrame"]
    if cursor < total:
        untouched.append({"startFrame": cursor, "endFrame": total})
    return {"schemaVersion": 1, "requestSha256": hashlib.sha256(canonical(request).encode()).hexdigest(),
        "clock": "body-frames", "fps": str(fps), "totalFrames": total,
        "master": request["master"], "selection": request["selection"],
        "clockEvidence": {"master": master_clock, "sources": source_clocks},
        "edits": edits, "untouched": untouched, "gaps": gaps, "reviewTasks": reviews,
        "options": options, "audio": "preserve-master", "reviewOnly": True,
        "status": "needs-review" if gaps or reviews else "geometry-ready-for-review",
        "limitations": ["Cutaway proposals only; no performance or lip-sync certification.",
            "Revalidate the complete request immediately before any application.",
            "Mixed-rate conversion must emit exactly outputFrames without looping or held padding."]}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--request", required=True, type=Path)
    parser.add_argument("--out", required=True, type=Path)
    args = parser.parse_args()
    try:
        request = json.loads(args.request.read_text())
        root = args.request.resolve().parent
        protected = [args.request.resolve()]
        for record in [request["master"], request["selection"], *[r["source"] for r in request.get("ranges", [])]]:
            path = Path(record["path"])
            protected.append((root / path).resolve() if not path.is_absolute() else path.resolve())
        if args.out.resolve() in protected:
            raise ValueError("output must not overwrite any input")
        result = build_plan(request, root)
        content = json.dumps(result, indent=2, allow_nan=False) + "\n"
        # Identical requests do not produce another plan or change its timestamp.
        if not args.out.exists() or args.out.read_text() != content:
            args.out.parent.mkdir(parents=True, exist_ok=True)
            args.out.write_text(content)
        print(json.dumps({"plan": str(args.out), "status": result["status"], "edits": len(result["edits"]), "gaps": len(result["gaps"])}))
    except (ValueError, KeyError, TypeError, OSError, subprocess.SubprocessError) as exc:
        parser.error(str(exc))


if __name__ == "__main__":
    main()
