#!/usr/bin/env python3
"""Pen detection on TAIL segments only (Jim 2026-11-07 14:1x):
  shipin1 tail from 1:20 (frame 2400) to end
  shipin3 tail from 1:00 (frame 1800) to end
Cancels/replaces the full-video pen_pass_s3 run.

Per video:
  1. cut tail clip from the original (frame-accurate, re-encode crf 18)
  2. SAM3 prompt 'marker pen' (conf 0.62 / det_thresh 0.50) on the tail clip
  3. rebase pen boxes to ORIGINAL frame numbers
  4. keep only pen boxes overlapping a hand box in the same frame
     (inter/pen_area >= 0.15 or IoU >= 0.10) using the merged hand boxes
Writes per video into data/out/<job>/:
  shipinN_tail.mp4, shipinN_tail_pen.boxes.json (raw, tail-relative frames),
  shipinN_tail_pen_filtered.boxes.json (original frame numbers),
  shipinN_tail_pen.summary.json
Merging into finals happens afterwards (separate step, after eye-check).

Usage (on the 19103 card):
  nohup ./run_py.sh pen_tail_detect.py > pen_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")
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.log")

TAILS = {
    "shipin1": {"job": "c3de403cfd15", "start_frame": 2400, "start_sec": 80.0},
    "shipin3": {"job": "fe165602b721", "start_frame": 1800, "start_sec": 60.0},
}
PROMPTS = [{"text": "marker pen", "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

    for stem, cfg in TAILS.items():
        job, start_frame, start_sec = cfg["job"], cfg["start_frame"], cfg["start_sec"]
        job_dir = os.path.join(OUT_DIR, job)
        src = os.path.join(UPLOADS, f"{stem}.mp4")
        tail_mp4 = os.path.join(job_dir, f"{stem}_tail.mp4")
        tail_bj = os.path.join(job_dir, f"{stem}_tail_pen.boxes.json")
        tail_status = os.path.join(job_dir, f"{stem}_tail_pen_status.json")
        filt_bj = os.path.join(job_dir, f"{stem}_tail_pen_filtered.boxes.json")
        summary_path = os.path.join(job_dir, f"{stem}_tail_pen.summary.json")
        hand_bj = os.path.join(job_dir, f"{stem}_hand_annotated.merged.boxes.json")
        try:
            # 1. cut tail clip (frame-accurate: -ss before -i + re-encode)
            log(f"[{stem}] cutting tail from {start_sec}s (frame {start_frame})")
            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"[{stem}] TAIL CUT FAILED:\n{r.stderr}")
                continue
            cap = cv2.VideoCapture(tail_mp4)
            nframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            cap.release()
            log(f"[{stem}] tail clip frames={nframes}")

            # 2. SAM3 marker pen on the tail clip
            log(f"[{stem}] running SAM3 prompt='marker pen' on tail ({nframes} frames)")
            hand_annotator.annotate(
                input_path=tail_mp4,
                output_path=os.path.join(job_dir, f"{stem}_tail_pen_annotated.mp4"),
                category="marker pen", 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"[{stem}] raw pen boxes={total} on {sum(1 for rw in rows if rw.get('boxes'))}/{len(rows)} tail frames")

            # 3+4. rebase to original frames + hand-overlap filter
            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": stem, "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"[{stem}] DONE kept={kept} boxes on {len(kept_frames)} frames, runs={runs}")
        except Exception:
            log(f"[{stem}] ERROR:\n{traceback.format_exc()}")
            continue
    log("[pen-tail] ALL DONE")


if __name__ == "__main__":
    main()
