#!/usr/bin/env python3
"""Eye-check the merged cap boxes (from shipin3_hand_pen_cap_full.boxes.json)
on 6 frames spread across the video, incl. the previously-gap segments
(S2 45-59s, S3 60-69s, S5 76-85s, S4 96-106s). Draws cap boxes only (purple)
so a wrong box is obvious. Uploads to OCS as cap_verify_f<frame>.jpg.
"""
import json
import os
import subprocess
import sys

PROJECT = "/home/agent/.claude/workspace/project"
OUT_DIR = os.path.join(PROJECT, "data", "out", "fe165602b721")
UPLOADS = os.path.join(PROJECT, "data", "uploads")
LOG_PATH = os.path.join(PROJECT, "cap_verify.log")
FRAMES = (300, 1400, 1600, 1900, 2400, 3000)


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 = {r["frame"]: r for r in json.load(
        open(os.path.join(OUT_DIR, "shipin3_hand_pen_cap_full.boxes.json")))}
    cap = cv2.VideoCapture(os.path.join(UPLOADS, "shipin3.mp4"))
    for fi in FRAMES:
        cap.set(cv2.CAP_PROP_POS_FRAMES, fi)
        ok, frame = cap.read()
        if not ok:
            log(f"frame {fi}: read failed")
            continue
        r = rows[fi]
        boxes = r.get("boxes") or []
        labels = r.get("labels") or []
        confs = r.get("conf") or []
        cap_boxes = [(b, c) for b, l, c in zip(boxes, labels, confs) if l == "cap"]
        log(f"frame {fi}: {len(cap_boxes)} cap boxes " +
            str([[round(v) for v in b] for b, _ in cap_boxes]))
        for b, c in cap_boxes:
            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_verify_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_verify_f{fi}.jpg"],
                           capture_output=True, text=True)
        log(f"frame {fi} uploaded HTTP {r.stdout.strip()}")
    cap.release()
    log("[verify] DONE")


if __name__ == "__main__":
    main()
