#!/usr/bin/env python3
"""Generate a 1:1 Windows XP SP3 LogonUI (logonui.exe) 1920x1080 background for hyprlock."""
import os
from PIL import Image, ImageDraw, ImageFont

W, H = 1920, 1080
ISO_BMP = "/home/carsten/.local/src/xp-iso-extracted/res/logonui/bitmaps"
WINTC = "/usr/local/share/wintc/logonui"
FONT_DIR = "/usr/local/share/fonts/truetype/wintc"
OUT_PATH = "/home/carsten/.config/hypr/assets/xp-logon-bg.png"

def load_font(name, size):
    p = os.path.join(FONT_DIR, name)
    if os.path.exists(p):
        return ImageFont.truetype(p, size)
    return ImageFont.load_default()

def key_magenta(im):
    im = im.convert("RGBA")
    px = im.load()
    for y in range(im.height):
        for x in range(im.width):
            r, g, b, a = px[x, y]
            if r > 240 and g < 15 and b > 240:
                px[x, y] = (0, 0, 0, 0)
    return im

def nine_slice(im, target_w, target_h, left=8, top=8, right=8, bottom=8):
    """9-slice stretch preserving crisp rounded corners and borders."""
    im = im.convert("RGBA")
    sw, sh = im.size
    out = Image.new("RGBA", (target_w, target_h), (0, 0, 0, 0))
    # Regions
    src_x = [0, left, sw - right, sw]
    src_y = [0, top, sh - bottom, sh]
    dst_x = [0, left, target_w - right, target_w]
    dst_y = [0, top, target_h - bottom, target_h]
    for r in range(3):
        for c in range(3):
            sx0, sx1 = src_x[c], src_x[c+1]
            sy0, sy1 = src_y[r], src_y[r+1]
            dx0, dx1 = dst_x[c], dst_x[c+1]
            dy0, dy1 = dst_y[r], dst_y[r+1]
            if sx1 <= sx0 or sy1 <= sy0 or dx1 <= dx0 or dy1 <= dy0:
                continue
            patch = im.crop((sx0, sy0, sx1, sy1))
            if (dx1 - dx0, dy1 - dy0) != patch.size:
                patch = patch.resize((dx1 - dx0, dy1 - dy0), Image.Resampling.BILINEAR)
            out.paste(patch, (dx0, dy0))
    return out

def main():
    canvas = Image.new("RGBA", (W, H), (90, 126, 220, 255))
    draw = ImageDraw.Draw(canvas)

    TOP_H = 80
    BOT_H = 96
    BOT_Y = H - BOT_H

    # 1. Top panel (#00309C) + glowing silver-white divider (125.png, 800x2)
    draw.rectangle([0, 0, W, TOP_H - 1], fill=(0, 48, 156, 255))
    hsepa = Image.open(f"{ISO_BMP}/125.png").convert("RGBA").resize((W, 2), Image.Resampling.BILINEAR)
    canvas.alpha_composite(hsepa, (0, TOP_H))

    # 2. Top-left radial spotlight (100.png, 219x207) right under top divider
    glow = Image.open(f"{ISO_BMP}/100.png").convert("RGBA")
    # Scale slightly (1.35x) so it feels proportional on 1080p while keeping seamless #5A7EDC fade
    glow = glow.resize((int(glow.width * 1.4), int(glow.height * 1.4)), Image.Resampling.BICUBIC)
    canvas.alpha_composite(glow, (0, TOP_H + 2))

    # 3. Bottom panel horizontal gradient (#3934AD -> #00309C) + glowing orange divider (126.png, 800x3)
    hsepb = Image.open(f"{ISO_BMP}/126.png").convert("RGBA").resize((W, 3), Image.Resampling.BILINEAR)
    canvas.alpha_composite(hsepb, (0, BOT_Y - 3))
    grad_row = Image.new("RGBA", (W, 1))
    gpx = grad_row.load()
    for x in range(W):
        t = x / float(W - 1)
        r = int(round(57 * (1 - t) + 0 * t))
        g = int(round(52 * (1 - t) + 48 * t))
        b = int(round(173 * (1 - t) + 156 * t))
        gpx[x, 0] = (r, g, b, 255)
    bot_strip = grad_row.resize((W, BOT_H), Image.Resampling.NEAREST)
    canvas.alpha_composite(bot_strip, (0, BOT_Y))

    # 4. Bottom-left: Turn off computer button (shtdbtn.png 26x26 + Arial 14pt white)
    shtd = Image.open(f"{WINTC}/shtdbtn.png").convert("RGBA")
    canvas.alpha_composite(shtd, (26, BOT_Y + (BOT_H - shtd.height) // 2))
    f_arial_14 = load_font("arial.ttf", 19)
    draw.text((26 + shtd.width + 9, BOT_Y + (BOT_H - 21) // 2), "Turn off computer", font=f_arial_14, fill=(255, 255, 255, 255))

    # 5. Bottom-right: exact rcstr(25) instructions in Tahoma 9pt white
    f_tahoma_9 = load_font("tahoma.ttf", 12)
    instruct = "After you log on, you can add or change accounts.\nJust go to Control Panel and click User Accounts."
    draw.multiline_text((W - 26 - 315, BOT_Y + (BOT_H - 32) // 2), instruct, font=f_tahoma_9, fill=(255, 255, 255, 255), spacing=4)

    # 6. Center vertical glowing divider (124.png 1x340 stretched vertically)
    MID_CY = (TOP_H + 2 + BOT_Y - 3) // 2  # 531
    vsep = Image.open(f"{ISO_BMP}/124.png").convert("RGBA").resize((1, 680), Image.Resampling.BILINEAR)
    canvas.alpha_composite(vsep, (W // 2, MID_CY - 340))

    # 7. Left side: Windows XP logo (123.png 137x86 exact #5A7EDC seamless bg) + "To begin, click your user name"
    LEFT_RIGHT_EDGE = W // 2 - 36  # x = 924
    logo = Image.open(f"{ISO_BMP}/123.png").convert("RGBA")
    logo_x = LEFT_RIGHT_EDGE - logo.width
    logo_y = MID_CY - 82  # y = 449
    canvas.alpha_composite(logo, (logo_x, logo_y))

    prompt_txt = "To begin, click your user name"
    bbox = draw.textbbox((0, 0), prompt_txt, font=f_arial_14)
    pw = bbox[2] - bbox[0]
    draw.text((LEFT_RIGHT_EDGE - pw, logo_y + logo.height + 18), prompt_txt, font=f_arial_14, fill=(239, 247, 255, 255))

    # 8. Right side: Selected user card (usersel.png 9-sliced to 372x86)
    CARD_X = W // 2 + 26   # x = 986
    CARD_W, CARD_H = 372, 86
    CARD_Y = MID_CY - CARD_H // 2  # y = 488
    usersel = Image.open(f"{WINTC}/usersel.png").convert("RGBA")
    card = nine_slice(usersel, CARD_W, CARD_H, left=10, top=10, right=10, bottom=10)
    canvas.alpha_composite(card, (CARD_X, CARD_Y))

    # 9. Selected golden-amber userpic frame (true 32-bit RGBA extracted from logonui.exe BMP 119) + chess userpic (48x48)
    frame = Image.open("/home/carsten/.config/hypr/assets/logon_frame_119.png").convert("RGBA")
    pic_path = "/usr/local/share/wintc/userpics/chess.png"
    userpic = Image.open(pic_path).convert("RGBA").resize((48, 48), Image.Resampling.LANCZOS)
    # Composite 32-bit RGBA golden border frame first, then 48x48 chess userpic cleanly inside at (5,5)
    framed = frame.copy()
    framed.alpha_composite(userpic, (5, 5))
    FRAME_X = CARD_X + 10
    FRAME_Y = CARD_Y + (CARD_H - framed.height) // 2  # 488 + 14 = 502
    canvas.alpha_composite(framed, (FRAME_X, FRAME_Y))

    # 10. Username ("carsten") + "Type your password"
    TEXT_X = FRAME_X + frame.width + 12  # 1066
    f_tahoma_14 = load_font("tahoma.ttf", 19)
    f_arial_8 = load_font("arial.ttf", 11)
    draw.text((TEXT_X, CARD_Y + 7), "carsten", font=f_tahoma_14, fill=(239, 247, 255, 255))
    draw.text((TEXT_X + 1, CARD_Y + 32), "Type your password", font=f_arial_8, fill=(255, 255, 255, 255))

    # 11. Password entry graphic (entry.png 171x26) + Go button (gobtn.png 26x26) + Hint button (hintbtn.png 28x28)
    ENTRY_X = TEXT_X       # 1066
    ENTRY_Y = CARD_Y + 48  # 536
    entry = Image.open(f"{WINTC}/entry.png").convert("RGBA")
    gobtn = Image.open(f"{WINTC}/gobtn.png").convert("RGBA")
    hintbtn = Image.open(f"{WINTC}/hintbtn.png").convert("RGBA")
    canvas.alpha_composite(entry, (ENTRY_X, ENTRY_Y))
    canvas.alpha_composite(gobtn, (ENTRY_X + entry.width + 5, ENTRY_Y))
    canvas.alpha_composite(hintbtn, (ENTRY_X + entry.width + 5 + gobtn.width + 4, ENTRY_Y - 1))

    # Save RGB PNG
    os.makedirs(os.path.dirname(OUT_PATH), exist_ok=True)
    canvas.convert("RGB").save(OUT_PATH, "PNG")

    # Compute exact hyprlock input-field center offset from (W/2, H/2) where +Y is UP
    cx = ENTRY_X + entry.width / 2.0
    cy = ENTRY_Y + entry.height / 2.0
    hx = round(cx - W / 2.0)
    hy = round(H / 2.0 - cy)
    print(f"Saved {OUT_PATH} ({W}x{H})")
    print(f"Entry box: ({ENTRY_X}, {ENTRY_Y}) size={entry.size} -> hyprlock position = {hx}, {hy}")

if __name__ == "__main__":
    main()
