#!/usr/bin/env python3
"""Pen tail run for shipin1 with the verified prompt 'paint marker'
(probe 2026-11-09: 4/5 sampled frames correct, boxes on the real white pen
with red PAINT lettering in the lower hand; 'whiteboard marker' dead).
Tail only: frames 2400-2682 (1:20 to end). Same flow as pen_tail_detect.py
but shipin1 only, new prompt, distinct output names (old 'marker pen' run
files are kept untouched).

Writes into data/out/c3de403cfd15/:
  shipin1_tail_paintmarker.mp4, shipin1_tail_paintmarker.boxes.json (raw),
  shipin1_tail_paintmarker_filtered.boxes.json (orig frame numbers, hand
  overlap filtered), shipin1_tail_paintmarker.summary.json

Usage (on the 19103 card):
  nohup ./run_py.sh pen_tail_v1.py > pen_tail_v1_stdout.log 2>&1 &
"""
import json
import os
import subprocess
import sys
import traceback

PROJECT = "/home/agent/.claude/workspace/project"
JOB_DIR = os.path.join(PROJECT, "data", "out", "c3de403cfd15")
UPLOADS = os.path.join(PROJECT, "data", "uploads")
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, "pen_tail_v1.log")

START_FRAME = 2400
START_SEC = 80.0
PROMPTS = [{"text": "paint marker", "conf": 0.62, "det_thresh": 0.50, "color": "yellow"}]


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


def area(b):
    return max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])


def inter(a, b):
    x0, y0 = max(a[0], b[0]), max(a[1], b[1])
    x1, y1 = min(a[2], b[2]), min(a[3], b[3])
    return max(0.0, x1 - x0) * max(0.0, y1 - y0)


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

    src = os.path.join(UPLOADS, "shipin1.mp4")
    tail_mp4 = os.path.join(JOB_DIR, "shipin1_tail_paintmarker.mp4")
    tail_bj = os.path.join(JOB_DIR, "shipin1_tail_paintmarker.boxes.json")
    tail_status = os.path.join(JOB_DIR, "shipin1_tail_paintmarker_status.json")
    filt_bj = os.path.join(JOB_DIR, "shipin1_tail_paintmarker_filtered.boxes.json")
    summary_path = os.path.join(JOB_DIR, "shipin1_tail_paintmarker.summary.json")
    hand_bj = os.path.join(JOB_DIR, "shipin1_hand_annotated.merged.boxes.json")
    try:
        log("[s1-tail] cutting tail from 80.0s (frame 2400)")
        r = subprocess.run(
            [FFMPEG, "-v", "error", "-ss", str(START_SEC), "-i", src,
             "-r", "30", "-c:v", "libx264", "-crf", "18", "-preset", "veryfast",
             "-c:a", "aac", "-y", tail_mp4],
            capture_output=True, text=True)
        if r.returncode != 0:
            log(f"[s1-tail] TAIL CUT FAILED:\n{r.stderr}")
            return
        cap = cv2.VideoCapture(tail_mp4)
        nframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        cap.release()
        log(f"[s1-tail] tail clip frames={nframes} (expect 282)")

        log("[s1-tail] running SAM3 prompt='paint marker' on tail")
        hand_annotator.annotate(
            input_path=tail_mp4,
            output_path=os.path.join(JOB_DIR, "shipin1_tail_paintmarker_annotated.mp4"),
            category="paint marker", status_path=tail_status, prompts=PROMPTS,
            boxes_json=tail_bj, verbose=False)
        rows = json.load(open(tail_bj))
        total = sum(len(rw.get("boxes") or []) for rw in rows)
        log(f"[s1-tail] raw pen boxes={total} on {sum(1 for rw in rows if rw.get('boxes'))}/{len(rows)} tail frames")

        hand_rows = json.load(open(hand_bj))
        hand_by_frame = {r["frame"]: (r.get("boxes") or []) for r in hand_rows}
        kept = 0
        kept_frames = []
        out_rows = []
        for rw in rows:
            boxes = rw.get("boxes") or []
            confs = rw.get("conf") or []
            ids = rw.get("ids") or []
            oframe = rw["frame"] + START_FRAME
            hand_boxes = hand_by_frame.get(oframe, [])
            k_boxes, k_confs, k_ids = [], [], []
            for b, c, i in zip(boxes, confs, ids):
                pa = area(b)
                keep = False
                for hb in hand_boxes:
                    ia = inter(b, hb)
                    if pa > 0 and (ia / pa >= 0.15 or ia / (pa + area(hb) - ia) >= 0.10):
                        keep = True
                        break
                if keep:
                    k_boxes.append(b)
                    k_confs.append(c)
                    k_ids.append(i)
            kept += len(k_boxes)
            if k_boxes:
                kept_frames.append(oframe)
            out_rows.append({"frame": oframe, "boxes": k_boxes, "conf": k_confs, "ids": k_ids})
        json.dump(out_rows, open(filt_bj, "w"))

        runs = []
        for f in kept_frames:
            if runs and f - runs[-1][1] <= 3:
                runs[-1][1] = f
            else:
                runs.append([f, f])
        top = []
        for rw in out_rows:
            for b, c in zip(rw["boxes"], rw["conf"]):
                top.append((c, rw["frame"], b))
        top.sort(reverse=True)
        summary = {
            "video": "shipin1", "prompt": "paint marker",
            "start_frame": START_FRAME, "start_sec": START_SEC,
            "tail_frames": nframes, "total_pen_boxes_raw": total,
            "kept_boxes": kept, "frames_with_kept_pen": len(kept_frames),
            "runs": runs,
            "top_conf": [[round(c, 2), f, [round(v) for v in b]] for c, f, b in top[:15]],
        }
        json.dump(summary, open(summary_path, "w"), indent=2)
        log(f"[s1-tail] DONE kept={kept} boxes on {len(kept_frames)} frames, runs={runs}")
    except Exception:
        log(f"[s1-tail] ERROR:\n{traceback.format_exc()}")


if __name__ == "__main__":
    main()
