#!/usr/bin/env python3
"""Render tails (hand+pen) and splice onto the previous hand-only finals.

Jim 2026-11-07: pen only in shipin1 tail (>=80s) and shipin3 tail (>=60s);
splice the new tails onto the previous finals instead of re-rendering all.
Runs on the 19103 card via run_py.sh, AFTER the eye-check of the filtered
pen boxes passes.

Per video:
  1. build combined tail boxes.json: hand (green) + filtered pen (yellow),
     frames rebased to tail-relative 0..
  2. render_from_boxes.py on the tail clip -> tail_rendered.mp4
  3. cut head from the previous hand final: 0..start_sec (re-encode)
  4. concat head + tail_rendered (re-encode) -> final hand+pen mp4
  5. verify frames == expected total and audio present; upload to OCS as
     视频1_hand_pen_annotated.mp4 / 视频3_hand_pen_annotated.mp4

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

PROJECT = "/home/agent/.claude/workspace/project"
OUT_DIR = os.path.join(PROJECT, "data", "out")
FFMPEG = "/home/agent/.local/lib/python3.11/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2"
LOG_PATH = os.path.join(PROJECT, "render_tail.log")
PROGRESS_PATH = os.path.join(PROJECT, "render_tail.progress")

VIDEOS = {
    # shipin1 deliberately EXCLUDED: eye-check 2026-11-07 (5/5 frames) showed
    # its pen boxes land on a small dark part in the upper hand while the real
    # white marker pen in the lower hand (f2434/f2435) is never boxed.
    # Its final stays the existing hand-only version; do not splice wrong boxes.
    "shipin3": {"job": "fe165602b721", "start_frame": 1800, "start_sec": 60.0,
                "total_frames": 3187, "ocs": "视频3_hand_pen_annotated.mp4"},
}


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


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)["video"])
                except Exception:
                    pass
    return done


def probe(path):
    import cv2
    cap = cv2.VideoCapture(path)
    nframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    cap.release()
    r = subprocess.run([FFMPEG, "-v", "info", "-i", path, "-f", "null", "-"],
                       capture_output=True, text=True)
    return {"frames": nframes, "fps": fps, "w": w, "h": h,
            "audio": "Audio:" in (r.stderr or "")}


def main():
    done = load_progress()
    log(f"[splice] starting, already done: {sorted(done)}")
    for stem, cfg in VIDEOS.items():
        if stem in done:
            log(f"[{stem}] skipped (already done)")
            continue
        job, sf, ss = cfg["job"], cfg["start_frame"], cfg["start_sec"]
        job_dir = os.path.join(OUT_DIR, job)
        tail_mp4 = os.path.join(job_dir, f"{stem}_tail.mp4")
        hand_bj = os.path.join(job_dir, f"{stem}_hand_annotated.merged.boxes.json")
        pen_bj = os.path.join(job_dir, f"{stem}_tail_pen_pruned.boxes.json")
        combined_bj = os.path.join(job_dir, f"{stem}_tail_combined.boxes.json")
        tail_rendered = os.path.join(job_dir, f"{stem}_tail_rendered.mp4")
        prev_final = os.path.join(job_dir, f"{stem}_hand_final.mp4")
        head_mp4 = os.path.join(job_dir, f"{stem}_head.mp4")
        final_mp4 = os.path.join(job_dir, f"{stem}_hand_pen_final.mp4")
        try:
            # 1. combined tail boxes (tail-relative frames)
            hand_rows = {r["frame"]: r for r in json.load(open(hand_bj))}
            pen_rows = {r["frame"]: r for r in json.load(open(pen_bj))}
            frames = sorted(set(list(hand_rows.keys()) + list(pen_rows.keys())))
            frames = [f for f in frames if f >= sf]
            out_rows = []
            for f in frames:
                boxes, confs, labels, colors = [], [], [], []
                hr = hand_rows.get(f, {})
                for b, c in zip(hr.get("boxes") or [], hr.get("conf") or []):
                    boxes.append(b); confs.append(c)
                    labels.append("hand"); colors.append("green")
                pr = pen_rows.get(f, {})
                for b, c in zip(pr.get("boxes") or [], pr.get("conf") or []):
                    boxes.append(b); confs.append(c)
                    labels.append("marker pen"); colors.append("yellow")
                out_rows.append({"frame": f - sf, "boxes": boxes, "conf": confs,
                                 "labels": labels, "colors": colors})
            json.dump(out_rows, open(combined_bj, "w"))
            log(f"[{stem}] combined tail boxes: {len(out_rows)} frames")

            # 2. render tail
            r = subprocess.run(
                [sys.executable, os.path.join(PROJECT, "render_from_boxes.py"),
                 "--video", tail_mp4, "--boxes", combined_bj, "--out", tail_rendered],
                capture_output=True, text=True)
            if r.returncode != 0:
                log(f"[{stem}] TAIL RENDER FAILED:\n{r.stdout}\n{r.stderr}")
                continue
            ti = probe(tail_rendered)
            log(f"[{stem}] tail rendered frames={ti['frames']} audio={'yes' if ti['audio'] else 'MISSING'}")

            # 3. cut head from previous final
            r = subprocess.run(
                [FFMPEG, "-v", "error", "-i", prev_final, "-t", str(ss),
                 "-c:v", "libx264", "-crf", "18", "-preset", "fast",
                 "-c:a", "aac", "-y", head_mp4],
                capture_output=True, text=True)
            if r.returncode != 0:
                log(f"[{stem}] HEAD CUT FAILED:\n{r.stderr}")
                continue
            hi = probe(head_mp4)
            log(f"[{stem}] head frames={hi['frames']} (expect {sf}) audio={'yes' if hi['audio'] else 'MISSING'}")
            if hi["frames"] != sf:
                log(f"[{stem}] HEAD FRAME COUNT MISMATCH, stop")
                continue

            # 4. concat head + tail
            lst = os.path.join(job_dir, f"{stem}_concat.txt")
            with open(lst, "w") as f:
                f.write(f"file '{head_mp4}'\nfile '{tail_rendered}'\n")
            r = subprocess.run(
                [FFMPEG, "-v", "error", "-f", "concat", "-safe", "0", "-i", lst,
                 "-c:v", "libx264", "-crf", "18", "-preset", "fast",
                 "-c:a", "aac", "-y", final_mp4],
                capture_output=True, text=True)
            if r.returncode != 0:
                log(f"[{stem}] CONCAT FAILED:\n{r.stderr}")
                continue
            fi = probe(final_mp4)
            size = os.path.getsize(final_mp4)
            log(f"[{stem}] final frames={fi['frames']} (expect {cfg['total_frames']}) "
                f"{fi['w']}x{fi['h']} audio={'yes' if fi['audio'] else 'MISSING'} size={size}")
            if fi["frames"] != cfg["total_frames"] or not fi["audio"]:
                log(f"[{stem}] VERIFY FAILED, not uploading")
                continue

            # 5. upload to OCS
            up = subprocess.run(
                ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                 "--upload-file", final_mp4,
                 f"https://ocs.dimond.top/{cfg['ocs']}"],
                capture_output=True, text=True)
            log(f"[{stem}] uploaded {cfg['ocs']}: HTTP {up.stdout.strip()}")
            if up.stdout.strip() != "201":
                log(f"[{stem}] UPLOAD FAILED")
                continue
            with open(PROGRESS_PATH, "a", encoding="utf-8") as f:
                f.write(json.dumps({"video": stem, "ocs": cfg["ocs"],
                                    "frames": fi["frames"], "size": size}) + "\n")
        except Exception:
            log(f"[{stem}] ERROR:\n{traceback.format_exc()}")
            continue
    log("[splice] ALL DONE")


if __name__ == "__main__":
    main()
