#!/usr/bin/env python3
"""Videos and stills of the parts of Vanta that are not apps, from the ROM's own assets:

  boot.mp4              out/bootanim/frames as bootanimation plays desc.txt (part1 looped twice)
  recovery-install.mp4  recovery's install screen: vendor/vanta/recovery loop frames centred on
                        black with the progress bar filling, laid out like ScreenRecoveryUI
  recovery-*.png        the header, fastbootd and switch art as recovery shows them
Usage: system_media.py OUTDIR
"""
import os, subprocess, sys, tempfile
from PIL import Image

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(ROOT, "docs/preview/system")
os.makedirs(OUT, exist_ok=True)


def ffmpeg(pattern, fps, dst):
    subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(fps), "-i", pattern,
                    "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "16", "-movflags", "+faststart", dst], check=True)
    print(dst)


def boot():
    fr = os.path.join(ROOT, "out/bootanim/frames")
    if not os.path.isdir(fr):
        subprocess.run([os.path.join(ROOT, "tools/bootanim/build.sh")], check=True, stdout=subprocess.DEVNULL)
    head = open(os.path.join(fr, "desc.txt")).read().split("\n")[0].split()
    fps = int(head[2])
    seq = []
    for line in open(os.path.join(fr, "desc.txt")).read().split("\n")[1:]:
        p = line.split()
        if len(p) < 4:
            continue
        files = sorted(os.listdir(os.path.join(fr, p[3])))
        loops = int(p[1]) or 2  # 0 = loop until boot completes; show it twice
        seq += [os.path.join(fr, p[3], f) for f in files] * loops
    with tempfile.TemporaryDirectory() as t:
        for i, f in enumerate(seq):
            os.symlink(f, os.path.join(t, f"{i:05d}.png"))
        ffmpeg(os.path.join(t, "%05d.png"), fps, os.path.join(OUT, "boot.mp4"))
    Image.open(seq[len(seq) // 2]).save(os.path.join(OUT, "boot.png"))


def recovery():
    img = os.path.join(ROOT, "vendor/vanta/recovery/res-xxxhdpi/images")
    loops = sorted(f for f in os.listdir(img) if f.startswith("loop"))
    W, H = 1080, 2640                      # Z Flip5 inner panel
    empty = Image.open(os.path.join(img, "progress_empty.png")).convert("RGB")
    fill = Image.open(os.path.join(img, "progress_fill.png")).convert("RGB")
    first = Image.open(os.path.join(img, loops[0]))
    ax, ay = (W - first.width) // 2, (H - first.height) // 2 - 120
    px, py = (W - empty.width) // 2, ay + first.height + 80
    n = 30 * 8
    with tempfile.TemporaryDirectory() as t:
        for i in range(n):
            frame = Image.new("RGB", (W, H), (0, 0, 0))
            frame.paste(Image.open(os.path.join(img, loops[i % len(loops)])).convert("RGB"), (ax, ay))
            frame.paste(empty, (px, py))
            w = int(fill.width * min(1.0, i / (n * 0.9)))
            if w:
                frame.paste(fill.crop((0, 0, w, fill.height)), (px, py))
            frame.save(os.path.join(t, f"{i:04d}.png"))
            if i == n // 2:
                frame.save(os.path.join(OUT, "recovery-install.png"))
        ffmpeg(os.path.join(t, "%04d.png"), 30, os.path.join(OUT, "recovery-install.mp4"))
    for name in ("logo_image", "fastbootd", "logo_image_switch"):
        Image.open(os.path.join(img, f"{name}.png")).save(os.path.join(OUT, f"recovery-{name.replace('_', '-')}.png"))


boot()
recovery()
