"""Measure three preselected, loop-intended public catalog clips."""
import hashlib
import argparse
import json
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

import imageio_ffmpeg
import numpy as np
from PIL import Image

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, default=Path('real-loop-clips'))
args = parser.parse_args()
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=True)
records = []
for clip_id in ["2041152430780637670", "2041684360483541236", "2040834865835250071"]:
    url = f"https://images.meigen.ai/videos/{clip_id}/video.mp4"
    path = out / (clip_id + ".mp4")
    record = {"id": clip_id, "url": url, "captured_at": datetime.now(timezone.utc).isoformat()}
    try:
        if not path.exists():
            with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}), timeout=40) as response:
                path.write_bytes(response.read())
        reader = imageio_ffmpeg.read_frames(str(path), pix_fmt="rgb24", output_params=["-fps_mode", "passthrough"])
        metadata = next(reader)
        width, height = metadata["size"]
        thumbs, identical_steps = [], []
        previous = first = last = None
        for index, raw in enumerate(reader):
            if first is None:
                first = raw
            if previous == raw:
                identical_steps.append(index)
            previous = last = raw
            picture = Image.frombytes("RGB", (width, height), raw).resize((128, 72), Image.Resampling.LANCZOS)
            thumbs.append(np.asarray(picture))
        frames = np.stack(thumbs).astype(np.float32)
        steps = np.abs(frames - np.roll(frames, 1, axis=0)).mean(axis=(1, 2, 3))
        selected = list(range(min(6, len(frames)))) + list(range(max(6, len(frames)-6), len(frames)))
        sheet = Image.new("RGB", (128*6, 72*2), "white")
        for position, index in enumerate(selected):
            sheet.paste(Image.fromarray(thumbs[index]), ((position%6)*128, (position//6)*72))
        sheet.save(out / (clip_id + "-endpoints.png"))
        record.update({"metadata": metadata, "frames": len(frames), "bytes": path.stat().st_size,
            "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "full_rgb_identical_interior_steps": identical_steps,
            "first_last_full_rgb_equal": first == last, "thumbnail_rgb_steps": steps.tolist(),
            "first_6_steps": steps[:6].tolist(), "last_6_steps": steps[-6:].tolist(),
            "method": "FFmpeg -fps_mode passthrough preserves decoded frame sequence. 128x72 RGB thumbnail mean absolute change; step0 compares last to first. Full RGB equality checked separately. No motion classifier or quality score."})
    except Exception as error:
        record["error"] = str(error)
    records.append(record)
    print(json.dumps({key: value for key, value in record.items() if key not in ["thumbnail_rgb_steps", "metadata"]}), flush=True)
(out / "real-loop-clips.json").write_text(json.dumps(records, indent=2), encoding="utf8")
if any("error" in record for record in records):
    raise SystemExit("One or more clips could not be measured; see real-loop-clips.json.")
