#!/usr/bin/env python3
"""Sample raw frames from shipin1/2/4 to see whether the black honeycomb
cover (under the blue battery modules) appears in each video, and where.
Exact-frame extraction via select filter (never -ss seconds: off by one).

Frames (30fps):
  shipin1 (2682f, 89.4s): 150, 900, 1800, 2550
  shipin2 (3262f, 108.7s): 150, 900, 1800, 2700, 3150
  shipin4 (2389f, 79.6s): 150, 900, 1800, 2250
Uploads to OCS as raw_v<N>_f<frame>.jpg, logs to raw_sample_v124.log.
"""
import os
import subprocess

PROJECT = "/home/agent/.claude/workspace/project"
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, "raw_sample_v124.log")

TARGETS = {
    1: [150, 900, 1800, 2550],
    2: [150, 900, 1800, 2700, 3150],
    4: [150, 900, 1800, 2250],
}


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


def main():
    for n, frames in TARGETS.items():
        src = os.path.join(UPLOADS, f"shipin{n}.mp4")
        for fi in frames:
            out = os.path.join(PROJECT, "data", "out",
                               f"raw_v{n}_f{fi}.jpg")
            r = subprocess.run(
                [FFMPEG, "-v", "error", "-i", src,
                 "-vf", f"select=eq(n\\,{fi})", "-vsync", "0",
                 "-frames:v", "1", "-y", out],
                capture_output=True, text=True)
            if r.returncode != 0 or not os.path.exists(out):
                log(f"v{n} f{fi}: EXTRACT FAILED {r.stderr[:200]}")
                continue
            u = subprocess.run(
                ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                 "--upload-file", out,
                 f"https://ocs.dimond.top/raw_v{n}_f{fi}.jpg"],
                capture_output=True, text=True)
            log(f"v{n} f{fi}: {os.path.getsize(out)} bytes, OCS HTTP {u.stdout.strip()}")
    log("[sample] DONE")


if __name__ == "__main__":
    main()
