#!/usr/bin/env python3
"""
Generate the Vanta boot animation frames (forked from failure-s10/bootanim;
same timing and part structure, Vanta wordmark in IBM Plex Sans).

Android's bootanimation player wants a zip of PNG sequences plus a desc.txt of
the form "<w> <h> <fps>" followed by one line per part. Everything here matches
what Infinity-X already ships on this device -- 1080x1080 at 60fps, three parts
typed 'c' -- because that combination is the one known to render correctly on
this panel, and a boot animation is the one surface with no way to iterate
without a reboot.

Frames are drawn at 2x and downsampled, which is the only antialiasing
available: the strokes here are 2-3px at final size and would crawl otherwise.
Glow is blurred on a quarter-size copy and scaled back up -- visually identical
to a full-resolution blur at these radii and about twenty times faster over
270 frames.
"""

import math
import os
import shutil
import sys

from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont

OUT = sys.argv[1] if len(sys.argv) > 1 else "build"

# --- geometry -------------------------------------------------------------
# Design coordinates are the final 1080x1080; SS is the supersample factor.
D = 1080
SS = 2
S = D * SS

FPS = 60
N_INTRO = 108   # 1.80 s
N_LOOP = 120    # 2.00 s, must be seamless
N_OUTRO = 42    # 0.70 s

# The loop's bloom gain swings between these. Both part boundaries are matched
# against LOOP_GAIN_HI, which is the loop's value at t=0 and at t=1.
LOOP_GAIN_LO = 0.80
LOOP_GAIN_HI = 1.30

# --- palette --------------------------------------------------------------
# Pure black, and the whole background plate is faded to zero before the
# square's edge. bootanimation centres this 1080x1080 on a 1440x3040 panel and
# clears the rest to true black, so ANY non-zero fill -- even (4,6,11) -- shows
# up as a visible grey rectangle floating on the screen. Verified by running
# bootanimation live on the device: the box was obvious.
BG = (0, 0, 0)
INK = (233, 238, 246)
CYAN = (53, 224, 255)
VIOLET = (139, 108, 255)
DIM = (62, 78, 102)   # reticle/rail furniture; 42,52,68 vanished at 1080

ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
FONT_MARK = os.path.join(ROOT, "vendor/vanta/fonts/IBMPlexSans-VF.ttf")
FONT_SUB = os.path.join(ROOT, "design/render/fonts/IBMPlexMono-Regular.woff2")
MARK_WEIGHT = 300  # the light cut the lock-screen clock uses
MARK_TRACK = 10.0  # light weights want air, not the -2.5 a semibold took

WORDMARK = "vanta"
SUBTITLE = "ANDROID 17"

# Vertical anchors in design space.
Y_MARK = 500
Y_RULE = 588
Y_SUB = 632
Y_RAIL = 716
RULE_W = 520
RAIL_W = 520


def px(v):
    return int(round(v * SS))


def font(path, size):
    return ImageFont.truetype(path, px(size))


F_MARK = font(FONT_MARK, 168)
F_MARK.set_variation_by_axes([MARK_WEIGHT, 100])
F_SUB = font(FONT_SUB, 25)


def ease_out(t):
    return 1 - (1 - t) ** 3


def ease_in_out(t):
    return 3 * t * t - 2 * t * t * t


def clamp01(t):
    return 0.0 if t < 0 else (1.0 if t > 1 else t)


def seg(t, a, b):
    """Rescale t from the window [a,b] onto [0,1], clamped."""
    if b <= a:
        return 1.0 if t >= b else 0.0
    return clamp01((t - a) / (b - a))


def colorize(mask, color, gain=1.0):
    """Tint an L mask into RGB, so it can be added onto the frame."""
    r, g, b = color
    lut_r = [min(255, int(i * r / 255 * gain)) for i in range(256)]
    lut_g = [min(255, int(i * g / 255 * gain)) for i in range(256)]
    lut_b = [min(255, int(i * b / 255 * gain)) for i in range(256)]
    return Image.merge("RGB", (mask.point(lut_r), mask.point(lut_g), mask.point(lut_b)))


def bloom(mask, radius, gain, down=4):
    small = mask.resize((mask.width // down, mask.height // down), Image.BILINEAR)
    small = small.filter(ImageFilter.GaussianBlur(radius / down))
    big = small.resize(mask.size, Image.BILINEAR)
    if gain == 1.0:
        return big
    lut = [min(255, int(i * gain)) for i in range(256)]
    return big.point(lut)


def tracked(draw, cx, cy, text, fnt, fill, tracking=0.0, upto=None):
    """Draw centred text with letter spacing PIL has no concept of.

    `upto` types the string out: a float count of glyphs to draw, where the
    fractional part fades the glyph that is currently arriving. Layout is
    always computed for the FULL string so the line does not slide while it
    types -- a centred string that re-centres per character reads as a bug.

    `fill` is either an RGB(A) tuple for a colour layer or a single int for an
    L-mode bloom mask; the per-glyph alpha has to be folded into the value in
    the second case, because an L image has no alpha channel to fold it into.
    """
    mono = isinstance(fill, int)
    base_a = 255 if mono else (fill[3] if len(fill) > 3 else 255)
    tr = tracking * SS
    widths = [draw.textlength(ch, font=fnt) for ch in text]
    total = sum(widths) + tr * (len(text) - 1)
    x = cx - total / 2
    n = len(text) if upto is None else upto
    for i, (ch, w) in enumerate(zip(text, widths)):
        if i + 1 <= n:
            f = 1.0
        elif i < n:
            f = n - i
        else:
            f = 0.0
        a = int(base_a * f)
        if a > 0 and ch != " ":
            ink = int(fill * f) if mono else fill[:3] + (a,)
            draw.text((x, cy), ch, font=fnt, fill=ink, anchor="lm")
        x += w + tr
    return total


def background():
    """Static plate: a cool vignette plus a faint scanline texture.

    Built once. The scanlines are 1 design pixel every 6 and sit at the edge of
    perceptible, which is the point -- they give the panel an instrument
    texture rather than looking like a flat fill.
    """
    # Radial lift toward the centre, drawn small and scaled up.
    w = 128
    vg = Image.new("L", (w, w), 0)
    d = ImageDraw.Draw(vg)
    cx = cy = w / 2
    for i in range(w // 2, 0, -1):
        v = int(30 * (1 - i / (w / 2)) ** 1.6)
        d.ellipse([cx - i, cy - i, cx + i, cy + i], fill=v)
    vg = vg.resize((S, S), Image.BICUBIC).filter(ImageFilter.GaussianBlur(8))

    sl = Image.new("L", (S, S), 0)
    d = ImageDraw.Draw(sl)
    for y in range(0, S, 6 * SS):
        d.line([(0, y), (S, y)], fill=18, width=SS)

    # Everything in the plate is gated by this falloff, which is exactly 0 at
    # the square's edge -- otherwise the scanline texture alone draws the
    # boundary of the 1080px canvas as a visible rectangle.
    fade = Image.new("L", (w, w), 0)
    fd = ImageDraw.Draw(fade)
    for i in range(w // 2, 0, -1):
        r = i / (w / 2)
        v = 255 if r < 0.44 else int(255 * max(0.0, (1 - (r - 0.44) / 0.50)) ** 1.5)
        fd.ellipse([cx - i, cy - i, cx + i, cy + i], fill=v)
    fade = fade.resize((S, S), Image.BICUBIC).filter(ImageFilter.GaussianBlur(10))

    plate = Image.new("RGB", (S, S), BG)
    plate = ImageChops.add(plate, colorize(vg, (90, 150, 255)))
    plate = ImageChops.add(plate, colorize(sl, (40, 70, 110)))
    return Image.composite(plate, Image.new("RGB", (S, S), (0, 0, 0)), fade)


BASE = background()


def reticle(draw, inset, alpha, color=DIM):
    """Four bracket corners framing the lock-up. `inset` eases them inward."""
    half_w = px(330) - inset
    top = px(Y_MARK - 118) + inset * 0.55
    bot = px(Y_RAIL + 46) - inset * 0.55
    cx = S / 2
    L, R = cx - half_w, cx + half_w
    arm = px(34)
    wd = max(1, px(1.6))
    col = color[:3] + (alpha,)
    for (x, sx) in ((L, 1), (R, -1)):
        for (y, sy) in ((top, 1), (bot, -1)):
            draw.line([(x, y), (x + arm * sx, y)], fill=col, width=wd)
            draw.line([(x, y), (x, y + arm * sy)], fill=col, width=wd)


def lockup(mark_alpha=255, sub_upto=None, ret_inset=0.0, ret_alpha=255,
           split=0.0, rule_frac=1.0):
    """The centre stack, as RGBA. Returns (layer, bright_mask).

    `split` is a chromatic offset in design pixels: a cyan copy pushed one way
    and a violet copy the other, easing to zero. `bright_mask` is what gets
    bloomed -- the wordmark and the accents, never the dim furniture, or the
    whole frame turns into fog.
    """
    layer = Image.new("RGBA", (S, S), (0, 0, 0, 0))
    d = ImageDraw.Draw(layer)
    cx = S / 2

    reticle(d, ret_inset, ret_alpha)

    if rule_frac > 0:
        half = px(RULE_W) / 2 * rule_frac
        d.line([(cx - half, px(Y_RULE)), (cx + half, px(Y_RULE))],
               fill=DIM + (ret_alpha,), width=max(1, px(1.4)))
        # Rail furniture, plus end ticks so the shuttle has somewhere to be.
        rhalf = px(RAIL_W) / 2 * rule_frac
        d.line([(cx - rhalf, px(Y_RAIL)), (cx + rhalf, px(Y_RAIL))],
               fill=DIM + (int(ret_alpha * 0.85),), width=max(1, px(2)))
        for sx in (-1, 1):
            x = cx + sx * rhalf
            d.line([(x, px(Y_RAIL - 7)), (x, px(Y_RAIL + 7))],
                   fill=DIM + (ret_alpha,), width=max(1, px(1.6)))

    if split > 0.4:
        for color, sx in ((CYAN, 1), (VIOLET, -1)):
            ghost = Image.new("RGBA", (S, S), (0, 0, 0, 0))
            gd = ImageDraw.Draw(ghost)
            tracked(gd, cx + sx * px(split), px(Y_MARK), WORDMARK, F_MARK,
                    color + (int(mark_alpha * 0.55),), tracking=MARK_TRACK)
            layer = Image.alpha_composite(layer, ghost)
            d = ImageDraw.Draw(layer)

    tracked(d, cx, px(Y_MARK), WORDMARK, F_MARK, INK + (mark_alpha,), tracking=MARK_TRACK)
    if sub_upto is None or sub_upto > 0:
        tracked(d, cx, px(Y_SUB), SUBTITLE, F_SUB, CYAN + (int(mark_alpha * 0.82),),
                tracking=6.5, upto=sub_upto)

    # Bright mask: redraw only the glowing parts into an L image.
    bright = Image.new("L", (S, S), 0)
    bd = ImageDraw.Draw(bright)
    tracked(bd, cx, px(Y_MARK), WORDMARK, F_MARK, int(mark_alpha), tracking=MARK_TRACK)
    tracked(bd, cx, px(Y_SUB), SUBTITLE, F_SUB, int(110 * mark_alpha / 255),
            tracking=6.5, upto=sub_upto)
    return layer, bright


def shuttle(t):
    """The travelling segment on the rail, as (layer, bright).

    Position is t plus a sine of the same period, so the loop is seamless in
    both value and velocity -- a linear sweep that snaps back at the wrap is
    the tell that a boot animation is looping.
    """
    layer = Image.new("RGBA", (S, S), (0, 0, 0, 0))
    bright = Image.new("L", (S, S), 0)
    d = ImageDraw.Draw(layer)
    bd = ImageDraw.Draw(bright)
    cx = S / 2
    half = px(RAIL_W) / 2
    seglen = px(152)
    pos = (t - 0.085 * math.sin(2 * math.pi * t)) % 1.0
    span = px(RAIL_W) + seglen
    head = cx - half - seglen + pos * span
    for (x0, x1) in ((head, head + seglen),
                     (head - span, head - span + seglen)):
        a = max(x0, cx - half)
        b = min(x1, cx + half)
        if b <= a:
            continue
        d.line([(a, px(Y_RAIL)), (b, px(Y_RAIL))], fill=CYAN + (255,), width=max(1, px(3)))
        bd.line([(a, px(Y_RAIL)), (b, px(Y_RAIL))], fill=235, width=max(1, px(3)))
    return layer, bright


def reveal(layer, y, soft):
    """Zero the alpha below a horizontal line, with a soft edge.

    This is the wipe: the lock-up only exists where the scan line has already
    been. Done on the alpha band only, so it costs one small paste per frame
    rather than a full-frame multiply.
    """
    a = layer.getchannel("A")
    d = ImageDraw.Draw(a)
    if y < S:
        d.rectangle([0, int(y), S, S], fill=0)
    # Feather the boundary so the edge does not stairstep at 1080.
    band = int(soft)
    if band > 0:
        y0 = max(0, int(y) - band)
        for i in range(band):
            yy = y0 + i
            if 0 <= yy < S:
                f = i / band
                row = a.crop((0, yy, S, yy + 1))
                row = row.point(lambda v, f=f: int(v * f))
                a.paste(row, (0, yy))
    layer.putalpha(a)
    return layer


def scanline(y, strength):
    """The sweeping line, plus its vertical bleed."""
    layer = Image.new("RGBA", (S, S), (0, 0, 0, 0))
    bright = Image.new("L", (S, S), 0)
    d = ImageDraw.Draw(layer)
    bd = ImageDraw.Draw(bright)
    w = px(372)
    cx = S / 2
    a = int(255 * strength)
    d.line([(cx - w, y), (cx + w, y)], fill=CYAN + (a,), width=max(1, px(2.4)))
    bd.line([(cx - w, y), (cx + w, y)], fill=int(250 * strength), width=max(1, px(2.4)))
    return layer, bright


def compose(content, bright, glow_radius=54, glow_gain=1.05, extra=None):
    im = BASE.copy()
    if content is not None:
        im = Image.alpha_composite(im.convert("RGBA"), content).convert("RGB")
    if extra is not None:
        im = Image.alpha_composite(im.convert("RGBA"), extra).convert("RGB")
    if bright is not None:
        g1 = bloom(bright, glow_radius, glow_gain)
        im = ImageChops.add(im, colorize(g1, CYAN, 0.42))
        g2 = bloom(bright, glow_radius * 3.2, glow_gain * 0.85, down=8)
        im = ImageChops.add(im, colorize(g2, VIOLET, 0.30))
    return im.resize((D, D), Image.LANCZOS)


def frame_intro(i, n):
    t = i / (n - 1)
    y0, y1 = px(Y_MARK - 190), px(Y_RAIL + 92)
    sy = y0 + (y1 - y0) * ease_out(seg(t, 0.0, 0.52))
    split = 13.0 * (1 - ease_out(seg(t, 0.34, 0.80)))
    sub_n = len(SUBTITLE) * seg(t, 0.56, 0.95)
    inset = px(46) * (1 - ease_out(seg(t, 0.10, 0.72)))
    ret_a = int(255 * seg(t, 0.10, 0.55))
    rule = ease_out(seg(t, 0.22, 0.70))

    content, bright = lockup(255, sub_n, inset, ret_a, split, rule)
    content = reveal(content, sy + px(3), px(16))
    bmask = bright.copy()
    bd = ImageDraw.Draw(bmask)
    if sy + px(3) < S:
        bd.rectangle([0, int(sy + px(3)), S, S], fill=0)

    # The line itself fades as it leaves the lock-up.
    st = 1.0 - 0.85 * seg(t, 0.52, 0.72)
    sl, slb = scanline(sy, st) if st > 0.02 else (None, None)
    if slb is not None:
        bmask = ImageChops.lighter(bmask, slb)
    # Ramp onto the loop's own opening gain over the last fifth, so the
    # part0 -> part1 cut is not a visible step in brightness.
    gain = 1.05 + (LOOP_GAIN_HI - 1.05) * ease_in_out(seg(t, 0.78, 1.0))
    return compose(content, bmask, 54, gain, extra=sl)


def frame_loop(i, n):
    t = i / n  # not n-1: frame n would equal frame 0
    breathe = 0.62 + 0.38 * (0.5 + 0.5 * math.cos(2 * math.pi * t))
    content, bright = lockup()
    sh, shb = shuttle(t)
    content = Image.alpha_composite(content, sh)
    bright = ImageChops.lighter(bright, shb)
    return compose(content, bright, 54, LOOP_GAIN_LO + (LOOP_GAIN_HI - LOOP_GAIN_LO) * breathe)


def frame_outro(i, n):
    """Bloom, hand the frame over to a single line, snap the line out.

    An earlier version scaled the stack vertically to collapse it, which
    squashed the letterforms and read as a rendering fault rather than a
    deliberate move. Cross-fading to a line through the wordmark's own centre
    gets the same gesture without ever distorting the type. The snap lands on
    the final frame, so the part does not sit on black -- 0.3 s of nothing
    before the launcher appears looks like a stall.
    """
    t = i / (n - 1)
    # Starts at the loop's terminal gain: part1 always finishes its iteration
    # (type 'c'), so the cut into part2 is deterministically frame 119 -> 0 and
    # a mismatch there is a visible flicker every single boot.
    swell = LOOP_GAIN_HI + 2.1 * ease_out(seg(t, 0.0, 0.34))
    fade = 1.0 - ease_in_out(seg(t, 0.22, 0.58))
    line_a = ease_out(seg(t, 0.18, 0.38))
    grow = ease_out(seg(t, 0.18, 0.55))
    snap = ease_in_out(seg(t, 0.60, 1.0))

    a = int(255 * fade)
    if a > 2:
        content, bright = lockup(mark_alpha=a, ret_alpha=a)
        sh, shb = shuttle(0.5)
        content = Image.alpha_composite(content, sh)
        bright = ImageChops.lighter(bright, shb)
        if fade < 1.0:
            lut = [int(v * fade) for v in range(256)]
            bright = bright.point(lut)
    else:
        content = Image.new("RGBA", (S, S), (0, 0, 0, 0))
        bright = Image.new("L", (S, S), 0)

    half = (px(210) + (px(392) - px(210)) * grow) * (1 - snap)
    if half > 1 and line_a > 0.01:
        d = ImageDraw.Draw(content)
        bd = ImageDraw.Draw(bright)
        la = int(255 * line_a)
        y = px(Y_MARK)
        d.line([(S / 2 - half, y), (S / 2 + half, y)],
               fill=INK + (la,), width=max(1, px(3.2)))
        bd.line([(S / 2 - half, y), (S / 2 + half, y)],
                fill=la, width=max(1, px(3.2)))

    return compose(content, bright, 60, swell)


PARTS = [
    ("part0", N_INTRO, frame_intro),
    ("part1", N_LOOP, frame_loop),
    ("part2", N_OUTRO, frame_outro),
]


def main():
    if os.path.isdir(OUT):
        shutil.rmtree(OUT)
    os.makedirs(OUT)

    with open(os.path.join(OUT, "desc.txt"), "w") as f:
        f.write(f"{D} {D} {FPS}\n")
        f.write("c 1 0 part0\n")
        f.write("c 0 0 part1\n")
        f.write("c 1 0 part2\n")

    total = 0
    for name, n, fn in PARTS:
        d = os.path.join(OUT, name)
        os.makedirs(d)
        for i in range(n):
            im = fn(i, n)
            im.save(os.path.join(d, f"boot_{i:04d}.png"), optimize=True)
            total += 1
            if (i + 1) % 20 == 0 or i + 1 == n:
                print(f"  {name}: {i + 1}/{n}", flush=True)
    print(f"{total} frames -> {OUT}")


if __name__ == "__main__":
    main()
