#!/usr/bin/env python3
"""Draw only the 'black honeycomb cover' prompt boxes from the probe
boxes.json onto 3 frames of the probe clip, for eye-checking.
Also prints the 2nd box coordinates per sampled frame.
"""
import json
import os
import subprocess
import sys

PROJECT = "/home/agent/.claude/workspace/project"
OUT_DIR = os.path.join(PROJECT, "data", "out", "fe165602b721")
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, "cap_probe_draw.log")


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


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

    rows = json.load(open(os.path.join(OUT_DIR, "cap_probe.boxes.json")))
    clip = os.path.join(OUT_DIR, "cap_probe_clip.mp4")
    cap = cv2.VideoCapture(clip)
    for fi in (0, 45, 89):
        cap.set(cv2.CAP_PROP_POS_FRAMES, fi)
        ok, frame = cap.read()
        if not ok:
            log(f"frame {fi}: read failed")
            continue
        rw = rows[fi]
        bs = ((rw.get("prompts") or {}).get("black honeycomb cover") or {}).get("boxes") or []
        cs = ((rw.get("prompts") or {}).get("black honeycomb cover") or {}).get("conf") or []
        log(f"clip frame {fi}: {len(bs)} cover boxes " + str([[round(v) for v in b] for b in bs]))
        for b, c in zip(bs, cs):
            x0, y0, x1, y1 = [int(v) for v in b]
            cv2.rectangle(frame, (x0, y0), (x1, y1), (255, 0, 255), 6)
            cv2.putText(frame, f"cap {c:.2f}", (x0, max(0, y0 - 12)),
                        cv2.FONT_HERSHEY_SIMPLEX, 1.4, (255, 0, 255), 3)
        out = f"/tmp/cap_probe_f{fi}.jpg"
        cv2.imwrite(out, frame, [cv2.IMWRITE_JPEG_QUALITY, 88])
        r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                            "--upload-file", out,
                            f"https://ocs.dimond.top/cap_probe_f{fi}.jpg"],
                           capture_output=True, text=True)
        log(f"frame {fi} uploaded HTTP {r.stdout.strip()}")
    cap.release()
    log("[draw] DONE")


if __name__ == "__main__":
    main()
