#!/usr/bin/env python3
"""Layer a preview the way the phone does: Vanta Liquid (the live wallpaper,
rendered from the ROM's shader) at the bottom, the app window (VantaHome's real
Compose render from tools/preview/HomeShots.kt, transparent where it draws
nothing) over it, and SystemUI's chrome on top: the Vanta Rail (patch 0001) and
a status bar line (time, ring battery; patch 0320).

  compose.py still UI.png OUT.png --dp 412 [--time 14] [--no-status]
  compose.py video FRAMEDIR OUT.mp4 --dp 412 [--time 14] [--no-status]
"""
import argparse, os, shutil, subprocess, sys, tempfile
from PIL import Image, ImageDraw, ImageFilter, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, HERE)
FONT = os.path.join(ROOT, "vendor/vanta/fonts/IBMPlexSans-VF.ttf")
ICE, EDGE = (207, 244, 255), (53, 224, 255)


def wallpaper(path, w, h, t, frames=0):
    cmd = [sys.executable, os.path.join(HERE, "wallpaper.py"), path, str(w), str(h), "--time", str(t)]
    if frames:
        cmd += ["--frames", str(frames)]
    subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)


def chrome(w, h, dp, status=True, rail=True, clock="21:35", battery=76):
    """SystemUI's layer: the Rail, and a minimal status bar."""
    s = w / dp
    layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    if not rail:
        return layer
    # Vanta Rail: 92 x 4 dp, 9 dp from the bottom, ice-white core with a cyan glow.
    rw, rh, rb = int(92 * s), max(2, int(4 * s)), int(9 * s)
    x0, y0 = (w - rw) // 2, h - rb - rh
    glow = Image.new("RGBA", (w, h), (0, 0, 0, 0))
    ImageDraw.Draw(glow).rounded_rectangle([x0 - 4 * s, y0 - 3 * s, x0 + rw + 4 * s, y0 + rh + 3 * s], radius=rh, fill=EDGE + (150,))
    layer = Image.alpha_composite(layer, glow.filter(ImageFilter.GaussianBlur(9 * s)))
    core = Image.new("RGBA", (rw, rh), (0, 0, 0, 0))
    px = core.load()
    for x in range(rw):
        f = x / max(1, rw - 1)
        a = max(0.0, 1 - abs(f - 0.5) * 2) ** 0.6
        c = tuple(int(ICE[i] + (255 - ICE[i]) * a) for i in range(3))
        for y in range(rh):
            px[x, y] = c + (int(255 * min(1, a * 1.4)),)
    mask = Image.new("L", (rw, rh), 0)
    ImageDraw.Draw(mask).rounded_rectangle([0, 0, rw - 1, rh - 1], radius=rh // 2, fill=255)
    core.putalpha(Image.composite(core.getchannel("A"), Image.new("L", (rw, rh), 0), mask))
    layer.alpha_composite(core, (x0, y0))
    if status:
        d = ImageDraw.Draw(layer)
        fs = int(14 * s)
        try:
            font = ImageFont.truetype(FONT, fs)
            font.set_variation_by_axes([500, 100])
        except Exception:
            font = ImageFont.load_default()
        top = int(10 * s)
        d.text((int(20 * s), top), clock, font=font, fill=(234, 246, 250, 255))
        r = int(7 * s)
        cx, cy = w - int(26 * s), top + fs // 2 + int(2 * s)
        d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(255, 255, 255, 40), width=max(2, int(2.2 * s)))
        d.arc([cx - r, cy - r, cx + r, cy + r], -90, -90 + 360 * battery / 100, fill=EDGE + (255,), width=max(2, int(2.2 * s)))
        bt = f"{battery}"
        tw = d.textlength(bt, font=font)
        d.text((cx - r - int(6 * s) - tw, top), bt, font=font, fill=(234, 246, 250, 255))
    return layer


def layer_one(ui, wall, top):
    out = Image.open(wall).convert("RGBA")
    out.alpha_composite(Image.open(ui).convert("RGBA"))
    out.alpha_composite(top)
    return out.convert("RGB")


def still(a):
    w, h = Image.open(a.src).size
    with tempfile.TemporaryDirectory() as t:
        wp = os.path.join(t, "wall.png")
        wallpaper(wp, w, h, a.time)
        layer_one(a.src, wp, chrome(w, h, a.dp, not a.no_status, not a.no_rail)).save(a.dst)
    print(a.dst)


def video(a):
    frames = sorted(f for f in os.listdir(a.src) if f.endswith(".png"))
    w, h = Image.open(os.path.join(a.src, frames[0])).size
    w2, h2 = w - w % 2, h - h % 2
    top = chrome(w, h, a.dp, not a.no_status, not a.no_rail)
    with tempfile.TemporaryDirectory() as t:
        wd = os.path.join(t, "wall")
        wallpaper(wd, w, h, a.time, frames=len(frames))
        od = os.path.join(t, "out")
        os.makedirs(od)
        for i, f in enumerate(frames):
            layer_one(os.path.join(a.src, f), os.path.join(wd, f"{i:04d}.png"), top).crop((0, 0, w2, h2)).save(os.path.join(od, f"{i:04d}.png"))
        subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-framerate", "30", "-i", os.path.join(od, "%04d.png"),
                        "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-movflags", "+faststart", a.dst], check=True)
    print(a.dst)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("mode", choices=["still", "video"])
    ap.add_argument("src"); ap.add_argument("dst")
    ap.add_argument("--dp", type=float, required=True, help="window width in dp (412 phone, 250 cover)")
    ap.add_argument("--time", type=float, default=14.0)
    ap.add_argument("--no-status", action="store_true")
    ap.add_argument("--no-rail", action="store_true",
                    help="Robolectric applies no system-bar insets, so on the cover the chrome would sit on content")
    a = ap.parse_args()
    (still if a.mode == "still" else video)(a)
