#!/usr/bin/env python3
"""Draw Vanta's recovery art: header logos, the install animation, progress bars.

LineageOS recovery loads its art by file name out of bootable/recovery/res-<dpi>/
images (the header is `logo_image`, `logo_image_switch` when fastbootd is a menu
away, `fastbootd` in fastbootd; the install animation is every `loop*.png` in
sort order at ro.recovery.ui.animation_fps). So branding recovery is drawing
files with the same names at the same sizes, and tools/recovery.sh swapping
them into the tree. Sizes are taken from the synced tree, so a density Lineage
adds or resizes shows up as a --check failure instead of a stretched logo.

Colours are design/tokens.json's `void` palette: cyan on true black, the warn
amber for fastbootd (Lineage's own fastbootd accent is amber too, so a user
who knows Lineage recovery still reads the mode at a glance).

Usage: tools/gen_recovery.py [--src TREE] [--check]
"""
import argparse
import glob
import io
import json
import math
import os
import re
import struct
import sys

try:  # --check runs on the build box, which has no PIL; only rendering needs it
    from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont
except ImportError:
    Image = None

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(HERE, "vendor/vanta/recovery")
TOK = json.load(open(os.path.join(HERE, "design/tokens.json")))
C = {k: tuple(int(v[i:i + 2], 16) for i in (0, 2, 4)) for k, v in TOK["void"]["colors"].items()}
FONT = os.path.join(HERE, "vendor/vanta/fonts/IBMPlexSans-VF.ttf")
MONO = os.path.join(HERE, "design/render/fonts/IBMPlexMono-Regular.woff2")
MASK = re.search(r"export const MASK = '([^']+)'",
                 open(os.path.join(HERE, "design/render/glyphs.js")).read()).group(1)
SS = 3
FRAMES = 30
HEADERS = ("logo_image", "logo_image_switch", "fastbootd")


def font(path, size, weight=None):
    f = ImageFont.truetype(path, max(1, int(size)))
    if weight is not None:
        f.set_variation_by_axes([weight, 100])
    return f


def png_size(path):
    with open(path, "rb") as f:
        head = f.read(24)
    return struct.unpack(">II", head[16:24])


def mask_points(n=720):
    """Sample the Vanta mask path (M/L/C/Z, 0..100 units) into a closed polyline."""
    toks = re.findall(r"[MLCZ]|-?\d+(?:\.\d+)?", MASK)
    segs, i, cur, start = [], 0, None, None
    while i < len(toks):
        t = toks[i]
        if t == "M":
            cur = start = (float(toks[i + 1]), float(toks[i + 2])); i += 3
        elif t == "L":
            p = (float(toks[i + 1]), float(toks[i + 2])); segs.append(("L", cur, p)); cur = p; i += 3
        elif t == "C":
            v = [float(x) for x in toks[i + 1:i + 7]]
            p = (v[4], v[5]); segs.append(("C", cur, (v[0], v[1]), (v[2], v[3]), p)); cur = p; i += 7
        elif t == "Z":
            if cur != start:
                segs.append(("L", cur, start))
            i += 1
        else:
            i += 1
    dense = []
    for s in segs:
        for k in range(64):
            u = k / 64
            if s[0] == "L":
                (x0, y0), (x1, y1) = s[1], s[2]
                dense.append((x0 + (x1 - x0) * u, y0 + (y1 - y0) * u))
            else:
                p0, p1, p2, p3 = s[1:]
                a, b, c, d = (1 - u) ** 3, 3 * (1 - u) ** 2 * u, 3 * (1 - u) * u * u, u ** 3
                dense.append((a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0],
                              a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]))
    # Resample evenly by arc length, so the sweep travels at constant speed.
    L = [0.0]
    for (x0, y0), (x1, y1) in zip(dense, dense[1:] + dense[:1]):
        L.append(L[-1] + math.hypot(x1 - x0, y1 - y0))
    out, j = [], 0
    for k in range(n):
        target = L[-1] * k / n
        while L[j + 1] < target:
            j += 1
        f = (target - L[j]) / max(1e-9, L[j + 1] - L[j])
        (x0, y0), (x1, y1) = dense[j], dense[(j + 1) % len(dense)]
        out.append((x0 + (x1 - x0) * f, y0 + (y1 - y0) * f))
    return out


PTS = mask_points() if Image else None


def tint(mask, color, gain=1.0):
    return Image.merge("RGB", [mask.point([min(255, int(i * c / 255 * gain)) for i in range(256)])
                               for c in color])


def glow(mask, radius):
    small = mask.resize((max(1, mask.width // 4), max(1, mask.height // 4)), Image.BILINEAR)
    return small.filter(ImageFilter.GaussianBlur(radius / 4)).resize(mask.size, Image.BILINEAR)


def tracked(d, cx, cy, text, fnt, fill, tracking):
    ws = [d.textlength(ch, font=fnt) for ch in text]
    x = cx - (sum(ws) + tracking * (len(text) - 1)) / 2
    for ch, w in zip(text, ws):
        d.text((x, cy), ch, font=fnt, fill=fill, anchor="lm")
        x += w + tracking


def header(kind, w, h):
    """One header logo: a lit pill carrying the wordmark, and the mode below it."""
    W, H = w * SS, h * SS
    s = W / 512
    accent = C["warn"] if kind == "fastbootd" else C["edge"]
    lines = Image.new("L", (W, H), 0)
    fill = Image.new("L", (W, H), 0)
    ld, fd = ImageDraw.Draw(lines), ImageDraw.Draw(fill)
    x0, x1, y0, y1 = 6 * s, W - 6 * s, H * 0.27, H * 0.73
    r = (y1 - y0) / 2
    ld.rounded_rectangle([x0, y0, x1, y1], radius=r, outline=255, width=max(1, int(2.4 * s)))
    cy = (y0 + y1) / 2
    tracked(fd, W / 2, cy, "vanta", font(FONT, 60 * s, 300), 255, 3.5 * s)
    if kind != "logo_image":
        rec_sel = kind == "logo_image_switch"
        # R: a diamond; F: a triangle -- Lineage's own grammar for the two modes.
        dx, dy, rr = x0 + r * 0.95, cy, 22 * s
        diamond = [(dx, dy - rr), (dx + rr, dy), (dx, dy + rr), (dx - rr, dy)]
        tx, ty, tr = x1 - r * 0.95, cy, 24 * s
        tri = [(tx, ty - tr), (tx + tr * 1.05, ty + tr * 0.8), (tx - tr * 1.05, ty + tr * 0.8)]
        glyph = font(FONT, 24 * s, 600)
        for shape, (gx, gy), label, sel in ((diamond, (dx, dy), "R", rec_sel),
                                             (tri, (tx, ty + tr * 0.22), "F", not rec_sel)):
            if sel:
                fd.polygon(shape, fill=255)
                fd.text((gx, gy), label, font=glyph, fill=0, anchor="mm")
                dot_y = y1 - 12 * s
                fd.ellipse([gx - 3.2 * s, dot_y - 3.2 * s, gx + 3.2 * s, dot_y + 3.2 * s], fill=255)
            else:
                ld.polygon(shape, outline=255, width=max(1, int(2.2 * s)))
                ld.text((gx, gy), label, font=glyph, fill=255, anchor="mm")
    caption = "FASTBOOTD" if kind == "fastbootd" else "RECOVERY"
    tracked(fd, W / 2, H * 0.875, caption, font(MONO, 26 * s), 255, 14 * s)

    bright = ImageChops.lighter(lines, fill)
    im = tint(glow(bright, 26 * s), accent, 0.55)
    im = ImageChops.add(im, tint(lines, accent))
    # Wordmark in ink, everything else in the accent.
    word = Image.new("L", (W, H), 0)
    tracked(ImageDraw.Draw(word), W / 2, cy, "vanta", font(FONT, 60 * s, 300), 255, 3.5 * s)
    rest = ImageChops.subtract(fill, word)
    im = ImageChops.add(im, tint(rest, accent))
    im = ImageChops.add(im, tint(word, C["text"]))
    return im.resize((w, h), Image.LANCZOS)


def loop_frame(i, size):
    """The install animation: the Vanta mask, with a light running its rim."""
    W = size * SS
    pad = W * 0.22
    sc = (W - 2 * pad) / 100
    pts = [(pad + x * sc, pad + y * sc) for x, y in PTS]
    base = Image.new("L", (W, W), 0)
    ImageDraw.Draw(base).line(pts + pts[:1], fill=70, width=max(1, int(W / 260)), joint="curve")
    run = Image.new("L", (W, W), 0)
    rd = ImageDraw.Draw(run)
    n = len(pts)
    head = int(n * i / FRAMES)
    tail = int(n * 0.30)
    for k in range(tail):
        a = (k / tail) ** 1.8
        p, q = pts[(head - k) % n], pts[(head - k - 1) % n]
        rd.line([q, p], fill=int(255 * a), width=max(1, int(W / 150)))
    v = Image.new("L", (W, W), 0)
    ImageDraw.Draw(v).text((W / 2, W / 2 + W * 0.01), "v", font=font(FONT, W * 0.30, 300), fill=235, anchor="mm")
    breathe = 0.75 + 0.25 * math.cos(2 * math.pi * i / FRAMES)
    im = tint(glow(run, W / 18), C["glow"], 0.85)
    im = ImageChops.add(im, tint(glow(v, W / 30), C["glow"], 0.35 * breathe))
    im = ImageChops.add(im, tint(base, C["edge_dim"], 1.6))
    im = ImageChops.add(im, tint(run, C["ice"]))
    im = ImageChops.add(im, tint(v, C["text"]))
    return im.resize((size, size), Image.LANCZOS)


def bar(w, h, lit):
    im = Image.new("RGB", (w, h), C["edge"] if lit else C["surface_hi"])
    return im


def png(im):
    b = io.BytesIO()
    im.save(b, "PNG", optimize=True)
    return b.getvalue()


def build(src):
    root = os.path.join(src, "bootable/recovery")
    dens = sorted(d for d in glob.glob(os.path.join(root, "res-*dpi")) if os.path.isdir(os.path.join(d, "images")))
    if not dens:
        raise SystemExit(f"gen_recovery: no res-*dpi/images under {root}")
    files = {}
    for d in dens:
        name = os.path.basename(d)
        img = os.path.join(d, "images")
        for h in HEADERS:
            w, hh = Image.open(os.path.join(img, h + ".png")).size
            files[f"{name}/images/{h}.png"] = png(header(h, w, hh))
        size = Image.open(os.path.join(img, "loop00000.png")).size[0]
        for i in range(FRAMES):
            files[f"{name}/images/loop{i:05d}.png"] = png(loop_frame(i, size))
        pw, ph = Image.open(os.path.join(img, "progress_fill.png")).size
        files[f"{name}/images/progress_fill.png"] = png(bar(pw, ph, True))
        files[f"{name}/images/progress_empty.png"] = png(bar(pw, ph, False))
    return files


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", default=os.path.join(HERE, "build/l24"))
    ap.add_argument("--check", action="store_true", help="fail if sizes/names drifted from the tree")
    a = ap.parse_args()
    if a.check:
        # Rendering is slow and PIL output is not byte-stable across versions,
        # so --check compares what matters: every file exists at the tree's size.
        root = os.path.join(a.src, "bootable/recovery")
        bad = []
        for d in sorted(glob.glob(os.path.join(root, "res-*dpi"))):
            name = os.path.basename(d)
            for f in [f"{h}.png" for h in HEADERS] + ["loop00000.png", "progress_fill.png"]:
                ours = os.path.join(OUT, name, "images", f)
                if not os.path.exists(ours) or png_size(ours) != png_size(os.path.join(d, "images", f)):
                    bad.append(f"{name}/{f}")
        print("gen_recovery: " + ("ok" if not bad else "DRIFT " + " ".join(bad)))
        return 1 if bad else 0
    files = build(a.src)
    for rel, data in files.items():
        p = os.path.join(OUT, rel)
        os.makedirs(os.path.dirname(p), exist_ok=True)
        open(p, "wb").write(data)
    print(f"gen_recovery: wrote {len(files)} files to {OUT}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
