"""Create original analytic row-sampling animation and hypothetical search artwork"""

import argparse
import json
import subprocess
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFont

parser = argparse.ArgumentParser()
parser.add_argument("output", type=Path)
parser.add_argument("--font", default="/System/Library/Fonts/Supplemental/Arial.ttf")
args = parser.parse_args()
out = args.output
out.mkdir(parents=True, exist_ok=True)
font_path = args.font


def text(d, xy, s, size=30, color="#dce9f5"):
    d.text(xy, s, font=ImageFont.truetype(font_path, size), fill=color)


W, H, FPS, N = 1920, 720, 24, 72
background = Image.new("RGB", (W, H), "#0c1524")
d = ImageDraw.Draw(background)
text(d, (50, 28), "ROLLING SHUTTER EFFECT", 24, "#5eead4")
text(d, (50, 72), "One motion   Three row timing patterns", 56)
labels = ["Equal time rows", "Top to bottom", "Bottom to top"]
for j, label in enumerate(labels):
    text(d, (j * 640 + 30, 175), label, 34)
text(d, (45, 640), "Original analytic point samples   24 ms first to last row   1200 px/s", 30)
text(
    d,
    (45, 685),
    "No exposure blur integration or camera metadata   Not repaired footage or AI model output",
    23,
)
x = np.arange(640)[None, :]
ys = np.arange(360)[:, None]
pipe = subprocess.Popen(
    [
        "ffmpeg",
        "-v",
        "error",
        "-y",
        "-f",
        "rawvideo",
        "-pix_fmt",
        "rgb24",
        "-s",
        f"{W}x{H}",
        "-r",
        str(FPS),
        "-i",
        "pipe:0",
        "-an",
        "-c:v",
        "libx264",
        "-crf",
        "18",
        "-pix_fmt",
        "yuv420p",
        "-movflags",
        "+faststart",
        str(out / "rolling-row-comparison.mp4"),
    ],
    stdin=subprocess.PIPE,
)
for i in range(N):
    im = background.copy()
    base = 160 + (i / FPS * 1200) % 320
    for j, sign in enumerate([0, 1, -1]):
        shift = sign * 1200 * 0.024 * (ys / 359 - 0.5)
        mask = np.abs((x - base - shift + 160) % 320 - 160) < 20
        panel = np.zeros((360, 640, 3), dtype=np.uint8)
        panel[:] = [23, 38, 58]
        panel[90] = [53, 80, 106]
        panel[270] = [53, 80, 106]
        panel[:, 160] = [53, 80, 106]
        panel[:, 480] = [53, 80, 106]
        panel[mask] = [94, 234, 212]
        im.paste(Image.fromarray(panel), (j * 640, 240))
    pipe.stdin.write(im.tobytes())
    if i == 36:
        im.save(out / "rolling-row-frame36.png")
        im.save(out / "rolling-row-frame36.webp", quality=94)
pipe.stdin.close()
assert pipe.wait() == 0
subprocess.run(
    [
        "ffmpeg",
        "-v",
        "error",
        "-y",
        "-i",
        str(out / "rolling-row-comparison.mp4"),
        "-ss",
        "1.5",
        "-frames:v",
        "1",
        str(out / "rolling-row-frame36.png"),
    ],
    check=True,
)
frame = Image.open(out / "rolling-row-frame36.png").convert("RGB")
frame.save(out / "rolling-row-frame36.webp", quality=94)
hero = Image.new("RGB", (1600, 900), "#0c1524")
hero.paste(frame.resize((1600, 600)), (0, 145))
d = ImageDraw.Draw(hero)
text(d, (45, 45), "See the skew without confusing it with blur", 46)
text(d, (45, 810), "Decoded frame 36 from the published original row timing animation", 26)
hero.save(out / "rolling-shutter-effect-guide-hero.webp", quality=92)
frame.resize((960, 360)).save(out / "rolling-row-poster.webp", quality=90)
(out / "rolling-row-comparison.vtt").write_text(
    "WEBVTT\n\n00:00.000 --> 00:03.000\nThree original moving post patterns compare equal-time rows top-down row timing and bottom-up row timing with no exposure blur integration\n"
)
# Native source artwork using the actual exported arithmetic records
hero = Image.new("RGB", (1600, 900), "#0c1524")
d = ImageDraw.Draw(hero)
text(d, (60, 40), "CO DIRECTOR CREATIVE SEARCH", 25, "#5eead4")
text(d, (60, 100), "Try a direction   Keep the evidence", 62)
text(d, (60, 190), "Same illustrative observations   Different exploration coefficient", 29)
for k, c in enumerate([0, 50]):
    record = json.loads((out / f"codirector-c{c}.json").read_text())
    left = 60 + k * 770
    d.rounded_rectangle(
        (left, 280, left + 710, 740), radius=24, fill="#17263a", outline="#35506a", width=2
    )
    text(d, (left + 30, 315), f"Coefficient {c}", 38, "#5eead4")
    for i, s in enumerate(record["stages"]):
        label = s["stage"].replace("_", " ").capitalize()
        chosen = s["selected"].replace("_", " ").capitalize()
        text(d, (left + 30, 400 + i * 100), label, 24, "#9aadc1")
        text(d, (left + 30, 435 + i * 100), chosen, 34)
text(
    d,
    (60, 810),
    "Original arithmetic study   Hypothetical scores   No cloud pipeline or AI video generated",
    25,
)
hero.save(out / "co-director-ai-video-workflow-guide-hero.webp", quality=92)
print("Rendered original row comparison and creative search artwork")
