#!/usr/bin/env python3
"""Rollout method A: loose-threshold re-run of the remaining 1-box segments.

Runs on the 19103 card via run_py.sh (sets LD_LIBRARY_PATH for cv2).
One process: imports hand_annotator.annotate (model loaded once if cached),
cuts each clip with ffmpeg, runs loose (conf 0.45 / det_thresh 0.35),
merges new boxes into the video's boxes.json (dedup IoU>=0.5 or inner>=0.75).

Clips: segments merged when the gap between 1-box runs is < 150 frames.
Each clip gets 30 frames (1s) of padding on each side for tracker context;
only frames inside the ORIGINAL segment ranges are merged back.

Progress: appends one line per finished clip to rollout_a.progress (JSONL)
and rewrites the video's .merged.boxes.json after every clip, so a restart
skips finished clips and loses at most the current clip.

Usage:
  nohup ./run_py.sh rollout_a.py > rollout_a.log 2>&1 &
"""
import json
import os
import subprocess
import sys
import traceback

PROJECT = "/home/agent/.claude/workspace/project"
FFMPEG = "/home/agent/.local/lib/python3.11/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2"
OUT_DIR = os.path.join(PROJECT, "data", "out")
UPLOADS = os.path.join(PROJECT, "data", "uploads")
PAD = 30  # padding frames each side

JOBS = {
    "shipin1": "c3de403cfd15",
    "shipin2": "4e8924d45d4b",
    "shipin3": "fe165602b721",
    "shipin4": "e9ff7e814d64",
}
TOTAL_FRAMES = {"shipin1": 2682, "shipin2": 3262, "shipin3": 3187, "shipin4": 2389}
# merged clips (gap < 150 frames); each clip lists the ORIGINAL segment ranges it covers
CLIPS = {
    "shipin1": [
        ((0, 128), [(0, 128)]),
        ((299, 384), [(299, 384)]),
        ((977, 1083), [(977, 1083)]),
        ((1327, 1457), [(1327, 1359), (1413, 1457)]),
        ((2230, 2365), [(2230, 2262), (2279, 2314), (2322, 2365)]),
        ((2438, 2633), [(2438, 2565), (2603, 2633)]),
    ],
    "shipin2": [
        ((1624, 1746), [(1624, 1746)]),
        ((1934, 1983), [(1934, 1983)]),
        ((2048, 2312), [(2048, 2103), (2185, 2247), (2261, 2312)]),
        ((2824, 3018), [(2824, 3018)]),
    ],
    "shipin3": [
        ((926, 985), [(926, 985)]),
        ((1034, 1671), [(1034, 1216), (1226, 1671)]),
        ((1787, 1824), [(1787, 1824)]),
        ((2243, 2297), [(2243, 2297)]),
        ((2448, 3150), [(2448, 2477), (2586, 2616), (2716, 3150)]),
    ],
    "shipin4": [
        ((332, 363), [(332, 363)]),
        ((1011, 1042), [(1011, 1042)]),
        ((2080, 2354), [(2080, 2278), (2300, 2354)]),
    ],
}

LOG_PATH = os.path.join(PROJECT, "rollout_a.log")
PROGRESS_PATH = os.path.join(PROJECT, "rollout_a.progress")


def log(msg):
    line = msg
    print(line, flush=True)
    with open(LOG_PATH, "a", encoding="utf-8") as f:
        f.write(line + "\n")


def iou(a, b):
    ax1, ay1, ax2, ay2 = a
    bx1, by1, bx2, by2 = b
    ix1, iy1 = max(ax1, bx1), max(ay1, by1)
    ix2, iy2 = min(ax2, bx2), min(ay2, by2)
    iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1)
    inter = iw * ih
    if inter <= 0:
        return 0.0, 0.0
    area_a = max(0, (ax2 - ax1)) * max(0, (ay2 - ay1))
    area_b = max(0, (bx2 - bx1)) * max(0, (by2 - by1))
    union = area_a + area_b - inter
    return (inter / union if union > 0 else 0.0,
            inter / min(area_a, area_b) if min(area_a, area_b) > 0 else 0.0)


def merge_clip_into(merged_rows, clip_rows, clip_start, seg_ranges):
    """Merge one clip's boxes into the in-memory merged rows.
    Only frames inside the original segment ranges are touched.
    Returns (frames_touched, net_boxes_added)."""
    by_frame = {r["frame"]: r for r in merged_rows}
    clip_by_frame = {r["frame"]: r for r in clip_rows}
    frames_touched = 0
    net_added = 0
    for seg_start, seg_end in seg_ranges:
        for f in range(seg_start, seg_end + 1):
            row = by_frame.get(f)
            if row is None:
                continue
            lrow = clip_by_frame.get(f - clip_start)
            if lrow is None:
                continue
            loose_boxes = lrow.get("boxes") or []
            loose_confs = lrow.get("conf") or []
            if not loose_boxes:
                continue
            before = len(row.get("boxes") or [])
            items = []
            for b, c in zip(row.get("boxes") or [], row.get("conf") or []):
                items.append((float(c), list(b), "orig"))
            for b, c in zip(loose_boxes, loose_confs):
                items.append((float(c), list(b), "loose"))
            items.sort(key=lambda x: -x[0])
            kept = []
            for conf, box, src in items:
                dup = False
                for kconf, kbox, ksrc in kept:
                    ov, inner = iou(box, kbox)
                    if ov >= 0.5 or inner >= 0.75:
                        dup = True
                        break
                if not dup:
                    kept.append((conf, box, src))
            after = len(kept)
            if after > before:
                frames_touched += 1
                net_added += after - before
                row["boxes"] = [b for _, b, _ in kept]
                row["conf"] = [c for c, _, _ in kept]
                row["ids"] = [None] * len(kept)
                row["labels"] = ["hand"] * len(kept)
                row["colors"] = ["green"] * len(kept)
                if isinstance(row.get("prompts"), dict):
                    row["prompts"]["hand"] = {"boxes": row["boxes"], "conf": row["conf"], "ids": row["ids"]}
    return frames_touched, net_added


def load_progress():
    done = set()
    if os.path.exists(PROGRESS_PATH):
        for line in open(PROGRESS_PATH, encoding="utf-8"):
            line = line.strip()
            if line:
                try:
                    done.add(json.loads(line)["clip"])
                except Exception:
                    pass
    return done


def main():
    sys.path.insert(0, PROJECT)
    import hand_annotator  # noqa: E402

    done = load_progress()
    log(f"[rollout] starting, already done: {sorted(done)}")
    for stem in ("shipin1", "shipin2", "shipin3", "shipin4"):
        job = JOBS[stem]
        job_dir = os.path.join(OUT_DIR, job)
        base_name = f"{stem}_hand_annotated.mp4.boxes.json"
        merged_path = os.path.join(job_dir, f"{stem}_hand_annotated.merged.boxes.json")
        orig_path = os.path.join(job_dir, base_name)
        # base: existing merged file if present (shipin2 already has the trial merged),
        # else the original (back it up to .orig first)
        if os.path.exists(merged_path):
            base_path = merged_path
            log(f"[{stem}] base = existing merged file")
        else:
            bak = orig_path + ".orig"
            if not os.path.exists(bak):
                os.replace(orig_path, bak)
                log(f"[{stem}] backed up original to {bak}")
            base_path = bak
        merged_rows = json.load(open(base_path))
        src_video = os.path.join(UPLOADS, f"{stem}.mp4")
        total = TOTAL_FRAMES[stem]
        for (cstart, cend), seg_ranges in CLIPS[stem]:
            clip_key = f"{stem}_{cstart}_{cend}"
            if clip_key in done:
                log(f"[{clip_key}] skipped (already done)")
                continue
            clip_start = max(0, cstart - PAD)
            clip_end = min(total - 1, cend + PAD)
            n_frames = clip_end - clip_start + 1
            clip_name = f"{stem}_seg{cstart}_{cend}"
            clip_path = os.path.join(UPLOADS, clip_name + ".mp4")
            out_mp4 = os.path.join(job_dir, f"rollout_{clip_name}_hand_annotated.mp4")
            clip_bj = out_mp4 + ".boxes.json"
            clip_status = os.path.join(job_dir, f"rollout_{clip_name}_status.json")
            try:
                log(f"[{clip_key}] cutting frames {clip_start}-{clip_end} ({n_frames}f)")
                r = subprocess.run(
                    [FFMPEG, "-v", "error", "-ss", str(clip_start / 30.0),
                     "-i", src_video, "-t", str(n_frames / 30.0), "-r", "30",
                     "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
                     "-c:a", "aac", "-y", clip_path],
                    capture_output=True, text=True, timeout=600)
                if r.returncode != 0:
                    log(f"[{clip_key}] CUT FAILED: {r.stderr[-500:]}")
                    continue
                log(f"[{clip_key}] running SAM3 loose (conf 0.45 / det_thresh 0.35)")
                hand_annotator.annotate(
                    input_path=clip_path, output_path=out_mp4, category="hand",
                    status_path=clip_status, conf=0.45, det_thresh=0.35,
                    boxes_json=clip_bj, verbose=False)
                clip_rows = json.load(open(clip_bj))
                ft, na = merge_clip_into(merged_rows, clip_rows, clip_start, seg_ranges)
                json.dump(merged_rows, open(merged_path, "w"), ensure_ascii=False)
                with open(PROGRESS_PATH, "a", encoding="utf-8") as f:
                    f.write(json.dumps({"clip": clip_key, "frames_touched": ft,
                                        "net_added": na}) + "\n")
                log(f"[{clip_key}] DONE frames_touched={ft} net_boxes_added={na}")
            except Exception:
                log(f"[{clip_key}] ERROR:\n{traceback.format_exc()}")
                continue
        log(f"[{stem}] all clips done; merged file: {merged_path}")
    log("[rollout] ALL DONE")


if __name__ == "__main__":
    main()
