"""Package an offline HTML app for Gumroad: cover 1280x720, thumbnail 600x600, zip with README + licence.
Usage: python pack.py <AppName> "<Tagline>" "<accent hex>" <shot.png> [extra files...]
Reads work/apps/<AppName>/<AppName>.html and work/apps/<AppName>/README.txt."""
import sys, zipfile, os
from PIL import Image, ImageDraw, ImageFont, ImageFilter

ROOT = os.path.dirname(os.path.abspath(__file__))
PROD = os.path.join(ROOT, "..", "..", "product")

def font(size, bold=True):
    for f in (["segoeuib.ttf", "arialbd.ttf"] if bold else ["segoeui.ttf", "arial.ttf"]):
        try: return ImageFont.truetype(os.path.join(r"C:\Windows\Fonts", f), size)
        except OSError: pass
    return ImageFont.load_default()

def hexc(h): h = h.lstrip("#"); return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))

def title_parts(name):
    return (name[:-2], name[-2:]) if name.endswith("Ur") else (name, "")

def cover(name, tag, acc, shot, out):
    W, H = 1280, 720
    im = Image.new("RGB", (W, H), (22, 24, 29)); d = ImageDraw.Draw(im)
    a, b = title_parts(name); f = font(92 if len(name) < 10 else 72)
    d.text((70, 120), a, font=f, fill="white")
    d.text((70 + d.textlength(a, font=f), 120), b, font=f, fill=hexc(acc))
    # wrap tagline
    ft = font(34, False); words = tag.split(); lines, cur = [], ""
    for w in words:
        if d.textlength((cur + " " + w).strip(), font=ft) > 440: lines.append(cur); cur = w
        else: cur = (cur + " " + w).strip()
    lines.append(cur)
    for i, l in enumerate(lines): d.text((72, 250 + i * 46), l, font=ft, fill=(200, 206, 216))
    pt = "Offline - no account - yours"; pf = font(26); pw = d.textlength(pt, font=pf)
    d.rounded_rectangle((72, 560, 72 + pw + 56, 620), 30, fill=hexc(acc))
    d.text((100, 573), pt, font=pf, fill="white")
    s = Image.open(shot).convert("RGB"); s.thumbnail((640, 520))
    sh = Image.new("RGBA", (s.width + 40, s.height + 40), (0, 0, 0, 0)); ImageDraw.Draw(sh).rectangle((20, 24, s.width + 20, s.height + 24), fill=(0, 0, 0, 160))
    sh = sh.filter(ImageFilter.GaussianBlur(12))
    x, y = W - s.width - 50, (H - s.height) // 2
    im.paste(sh, (x - 20, y - 20), sh); im.paste(s, (x, y))
    im.save(os.path.join(out, "cover-1280x720.png"))

def thumb(name, acc, out):
    im = Image.new("RGB", (600, 600), (22, 24, 29)); d = ImageDraw.Draw(im)
    a, b = title_parts(name); f = font(110 if len(name) < 9 else 84)
    w = d.textlength(a + b, font=f); x = (600 - w) / 2
    d.text((x, 220), a, font=f, fill="white"); d.text((x + d.textlength(a, font=f), 220), b, font=f, fill=hexc(acc))
    d.rectangle((0, 560, 600, 600), fill=hexc(acc))
    im.save(os.path.join(out, "thumbnail-600.png"))

LICENCE = """LICENCE
You may use this app for personal and commercial work (run your business with it).
You may not resell, share or redistribute the app file itself.
Provided as-is with no warranty. Your data stays in your own browser on your own computer.
"""

def main():
    name, tag, acc, shot = sys.argv[1:5]; extras = sys.argv[5:]
    src = os.path.join(ROOT, name); out = os.path.join(PROD, name.lower()); os.makedirs(out, exist_ok=True)
    cover(name, tag, acc, shot, out); thumb(name, acc, out)
    with zipfile.ZipFile(os.path.join(out, name + ".zip"), "w", zipfile.ZIP_DEFLATED) as z:
        z.write(os.path.join(src, name + ".html"), name + "/" + name + ".html")
        z.write(os.path.join(src, "README.txt"), name + "/README.txt")
        z.writestr(name + "/LICENCE.txt", LICENCE)
        for e in extras: z.write(e, name + "/" + os.path.basename(e))
    print("packed", out, os.listdir(out))

if __name__ == "__main__":
    main()
