#!/usr/bin/env python3
"""Turn a Craft-app web release folder (PhotoCraft, DesignCraft, FilmCraft, ...) into an
installable Progressive Web App that keeps working with no network at all.

No extra packages needed: plain Python 3.8+.

  python3 make-pwa.py SITE_DIR [--name NAME] [--display fullscreen|standalone] [--icon icon.png]
      Adds a web app manifest, a service worker that stores every file of the app on the
      device, and home-screen icons; then links them from index.html. Safe to run again
      (after replacing the release with a newer one, run it again so phones pick up the update).

  python3 make-pwa.py serve SITE_DIR --cert cert.pem --key key.pem [--port 8443]
      Serves the folder over HTTPS (a service worker, and so offline install, needs HTTPS
      unless the page is opened from the same machine as http://localhost).

  SITE_DIR may also be a folder holding several app folders (serve Craft serves Craft/photocraft/ etc.).

It also fixes the PhotoCraft 0.17.0 release bug where app/photocraft-web.js can't find its
snippets/ folder.
"""

import argparse
import hashlib
import html
import json
import re
import shutil
import struct
import sys
import urllib.parse
import zlib
from pathlib import Path

MARK_START = "<!-- pwa:start -->"
MARK_END = "<!-- pwa:end -->"
GENERATED = {"sw.js"}
SKIP_NAMES = {".htaccess", "_headers", ".DS_Store", "Thumbs.db"}
SKIP_SUFFIXES = {".md"}

# --------------------------------------------------------------------------- snippets fix


def fix_snippets(site: Path) -> list:
    """Copy snippet folders that app/*.js imports but that only exist at the site root,
    and refresh copies left over from an older release."""
    fixed = []
    app = site / "app"
    if not app.is_dir():
        return fixed
    for glue in app.glob("*.js"):
        text = glue.read_text(encoding="utf-8", errors="replace")
        for rel in sorted(set(re.findall(r"""['"]\./(snippets/[^'"]+)['"]""", text))):
            folder = Path(rel).parts[1]
            src_dir, dst_dir = site / "snippets" / folder, app / "snippets" / folder
            if not src_dir.is_dir():
                continue
            stale = [f for f in src_dir.rglob("*") if f.is_file()
                     and (not (dst_dir / f.relative_to(src_dir)).is_file()
                          or (dst_dir / f.relative_to(src_dir)).read_bytes() != f.read_bytes())]
            if stale:
                shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True)
                fixed.append(f"app/snippets/{folder}")
    return fixed


# --------------------------------------------------------------------------- icons

FONT = {  # 5x7 capitals, for the generated icon's letter
    "A": "01110 10001 10001 11111 10001 10001 10001", "B": "11110 10001 10001 11110 10001 10001 11110",
    "C": "01110 10001 10000 10000 10000 10001 01110", "D": "11110 10001 10001 10001 10001 10001 11110",
    "E": "11111 10000 10000 11110 10000 10000 11111", "F": "11111 10000 10000 11110 10000 10000 10000",
    "G": "01110 10001 10000 10111 10001 10001 01111", "H": "10001 10001 10001 11111 10001 10001 10001",
    "I": "01110 00100 00100 00100 00100 00100 01110", "J": "00111 00010 00010 00010 00010 10010 01100",
    "K": "10001 10010 10100 11000 10100 10010 10001", "L": "10000 10000 10000 10000 10000 10000 11111",
    "M": "10001 11011 10101 10101 10001 10001 10001", "N": "10001 10001 11001 10101 10011 10001 10001",
    "O": "01110 10001 10001 10001 10001 10001 01110", "P": "11110 10001 10001 11110 10000 10000 10000",
    "Q": "01110 10001 10001 10001 10101 10010 01101", "R": "11110 10001 10001 11110 10100 10010 10001",
    "S": "01111 10000 10000 01110 00001 00001 11110", "T": "11111 00100 00100 00100 00100 00100 00100",
    "U": "10001 10001 10001 10001 10001 10001 01110", "V": "10001 10001 10001 10001 10001 01010 00100",
    "W": "10001 10001 10001 10101 10101 10101 01010", "X": "10001 10001 01010 00100 01010 10001 10001",
    "Y": "10001 10001 01010 00100 00100 00100 00100", "Z": "11111 00001 00010 00100 01000 10000 11111",
}


def write_png(path: Path, size: int, pixel) -> None:
    rows = bytearray()
    for y in range(size):
        rows.append(0)
        for x in range(size):
            rows.extend(pixel(x, y))
    chunk = lambda kind, data: struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
    png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0))
    png += chunk(b"IDAT", zlib.compress(bytes(rows), 9)) + chunk(b"IEND", b"")
    path.write_bytes(png)


def hue_rgb(name: str):
    import colorsys
    h = int(hashlib.sha256(name.encode()).hexdigest()[:4], 16) / 0xFFFF
    r, g, b = colorsys.hls_to_rgb(h, 0.42, 0.55)
    return int(r * 255), int(g * 255), int(b * 255)


def make_icon(path: Path, size: int, letter: str, color, full_bleed: bool) -> None:
    glyph = [row for row in FONT.get(letter, FONT["P"]).split()]
    # Letter fills the middle; a maskable icon keeps it inside the central safe zone.
    cell = size * (0.075 if full_bleed else 0.095)
    gw, gh = 5 * cell, 7 * cell
    ox, oy = (size - gw) / 2, (size - gh) / 2
    radius = size * 0.22
    clear, bg, fg = (0, 0, 0, 0), (*color, 255), (255, 255, 255, 255)

    def inside_rounded(x, y):
        if full_bleed:
            return True
        cx = min(max(x + 0.5, radius), size - radius)
        cy = min(max(y + 0.5, radius), size - radius)
        return (x + 0.5 - cx) ** 2 + (y + 0.5 - cy) ** 2 <= radius ** 2

    def pixel(x, y):
        if not inside_rounded(x, y):
            return clear
        gx, gy = int((x - ox) // cell), int((y - oy) // cell)
        if 0 <= gx < 5 and 0 <= gy < 7 and x >= ox and y >= oy and glyph[gy][gx] == "1":
            return fg
        return bg

    write_png(path, size, pixel)


def png_size(path: Path):
    head = path.read_bytes()[:24]
    if head[:8] != b"\x89PNG\r\n\x1a\n":
        sys.exit(f"error: {path} is not a PNG")
    return struct.unpack(">II", head[16:24])


# --------------------------------------------------------------------------- service worker

SW_TEMPLATE = r"""// Generated by make-pwa.py: keeps every file of this app on the device so it runs offline.
const VERSION = %(version)s;
const FILES = %(files)s;
const PREFIX = 'pwa:' + self.registration.scope + ':';
const CACHE = PREFIX + VERSION;
const url = (f) => new URL(f, self.registration.scope).href;

self.addEventListener('install', (event) => {
  event.waitUntil((async () => {
    const cache = await caches.open(CACHE);
    await cache.addAll(FILES.map((f) => new Request(url(f), { cache: 'reload' })));
    // No skipWaiting(): a new version takes over only after every window of the app is closed,
    // so a running app never mixes files from two releases.
  })());
});

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    for (const key of await caches.keys()) {
      if (key.startsWith(PREFIX) && key !== CACHE) await caches.delete(key);
    }
  })());
});

self.addEventListener('fetch', (event) => {
  const req = event.request;
  if (req.method !== 'GET' || new URL(req.url).origin !== self.location.origin) return;
  event.respondWith((async () => {
    const cache = await caches.open(CACHE);
    const hit = req.mode === 'navigate'
      ? await cache.match(url('index.html'))
      : await cache.match(req, { ignoreSearch: true });
    if (hit) return hit;
    try {
      return await fetch(req);
    } catch (e) {
      // Offline and not stored (an optional file such as fonts/manifest.txt): answer like a
      // server that doesn't have it, which the app already handles.
      return new Response('', { status: 404, statusText: 'Not Found (offline)' });
    }
  })());
});
"""


def site_files(site: Path) -> list:
    files = []
    for p in sorted(site.rglob("*")):
        if not p.is_file():
            continue
        rel = p.relative_to(site).as_posix()
        if rel in GENERATED or p.name in SKIP_NAMES or p.suffix.lower() in SKIP_SUFFIXES:
            continue
        if any(part.startswith(".") for part in Path(rel).parts):
            continue
        files.append(rel)
    return files


# --------------------------------------------------------------------------- build


def build(args) -> None:
    site = Path(args.site).resolve()
    index = site / "index.html"
    if not index.is_file():
        sys.exit(f"error: {index} not found; point this at the folder that holds index.html")
    page = index.read_text(encoding="utf-8")
    if MARK_START not in page and "</head>" not in page:
        sys.exit("error: index.html has no </head>")
    if args.icon:
        png_size(Path(args.icon))  # exits if it isn't a PNG

    for f in fix_snippets(site):
        print(f"copied {f}/ from snippets/ (the app loads it from there)")

    title_match = re.search(r"<title>(.*?)</title>", page, re.S)
    name = args.name or (html.unescape(title_match.group(1)).strip() if title_match else site.name)
    short = args.short_name or name
    bg = args.color
    letter = next((c for c in name.upper() if c in FONT), "P")

    icons_dir = site / "icons"
    icons_dir.mkdir(exist_ok=True)
    icons = []
    if args.icon:
        src = Path(args.icon)
        w, h = png_size(src)
        if src.resolve() != (icons_dir / "custom.png").resolve():
            shutil.copyfile(src, icons_dir / "custom.png")
        for old in ("icon-192.png", "icon-512.png", "icon-maskable-512.png"):
            (icons_dir / old).unlink(missing_ok=True)
        icons.append({"src": "icons/custom.png", "sizes": f"{w}x{h}", "type": "image/png", "purpose": "any"})
        head_icon = "icons/custom.png"
    else:
        (icons_dir / "custom.png").unlink(missing_ok=True)
        color = hue_rgb(name)
        for size in (192, 512):
            make_icon(icons_dir / f"icon-{size}.png", size, letter, color, full_bleed=False)
            icons.append({"src": f"icons/icon-{size}.png", "sizes": f"{size}x{size}", "type": "image/png", "purpose": "any"})
        make_icon(icons_dir / "icon-maskable-512.png", 512, letter, color, full_bleed=True)
        icons.append({"src": "icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"})
        head_icon = "icons/icon-192.png"

    manifest = {
        "name": name,
        "short_name": short,
        # index.html, not the folder: phone file-manager servers show a file list for a folder.
        "start_url": "index.html",
        "scope": "./",
        "display": args.display,
        "display_override": [args.display, "standalone"],
        "background_color": bg,
        "theme_color": bg,
        "icons": icons,
    }
    (site / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")

    block = "\n".join([
        MARK_START,
        '  <link rel="manifest" href="manifest.json">',
        f'  <meta name="theme-color" content="{bg}">',
        f'  <link rel="icon" href="{head_icon}">',
        f'  <link rel="apple-touch-icon" href="{head_icon}">',
        "  <script>",
        "    if ('serviceWorker' in navigator) {",
        "      navigator.serviceWorker.register('./sw.js').catch((e) => console.warn('offline install unavailable:', e));",
        "      if (navigator.storage && navigator.storage.persist) navigator.storage.persist();",
        "    }",
        "  </script>",
        "  " + MARK_END,
    ])
    if MARK_START in page:
        page = re.sub(re.escape(MARK_START) + r".*?" + re.escape(MARK_END), lambda _: block, page, flags=re.S)
    elif "</head>" in page:
        page = page.replace("</head>", "  " + block + "\n</head>", 1)
    else:
        sys.exit("error: index.html has no </head>")
    index.write_text(page, encoding="utf-8")

    files = site_files(site)
    digest = hashlib.sha256()
    for rel in files:
        digest.update(rel.encode() + b"\0")
        digest.update(hashlib.sha256((site / rel).read_bytes()).digest())
    version = digest.hexdigest()[:16]
    # Navigations are answered with index.html, so the folder URL needn't be stored.
    precache = [urllib.parse.quote(f) for f in files]
    (site / "sw.js").write_text(SW_TEMPLATE % {"version": json.dumps(version), "files": json.dumps(precache, indent=2)}, encoding="utf-8")

    total = sum((site / f).stat().st_size for f in files)
    print(f"{name}: {len(files)} files ({total / 1048576:.1f} MiB) stored for offline use, version {version}")
    print(f"display: {args.display}; icon letter '{letter}'" if not args.icon else f"display: {args.display}; custom icon")
    print("Open it at http://localhost (or over trusted HTTPS), let it load, reload once, then add it to the home screen.")


# --------------------------------------------------------------------------- HTTPS server


def serve(args) -> None:
    import http.server
    import mimetypes
    import ssl
    from functools import partial

    site = Path(args.site).resolve()
    if not site.is_dir():
        sys.exit(f"error: {site} is not a folder")
    for ext, mime in {".wasm": "application/wasm", ".js": "text/javascript", ".json": "application/json",
                      ".webmanifest": "application/manifest+json", ".png": "image/png"}.items():
        mimetypes.add_type(mime, ext)

    class Handler(http.server.SimpleHTTPRequestHandler):
        extensions_map = {**http.server.SimpleHTTPRequestHandler.extensions_map,
                          ".wasm": "application/wasm", ".js": "text/javascript"}

        def end_headers(self):
            # The service worker and page must be re-checked so updates reach installed copies.
            if self.path.split("?")[0].endswith(("/", "/index.html", "/sw.js")):
                self.send_header("Cache-Control", "no-cache")
            super().end_headers()

    httpd = http.server.ThreadingHTTPServer((args.bind, args.port), partial(Handler, directory=str(site)))
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(args.cert, args.key)
    # Handshake in each connection's own thread, so one idle client can't stall the others.
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True, do_handshake_on_connect=False)
    print(f"Serving {site} on https://{args.bind}:{args.port}/  (Ctrl+C to stop)")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass


def main() -> None:
    if len(sys.argv) > 1 and sys.argv[1] == "serve":
        p = argparse.ArgumentParser(prog="make-pwa.py serve", description="Serve a site folder over HTTPS.")
        p.add_argument("site")
        p.add_argument("--cert", required=True, help="certificate PEM (e.g. from mkcert)")
        p.add_argument("--key", required=True, help="private key PEM")
        p.add_argument("--port", type=int, default=8443)
        p.add_argument("--bind", default="0.0.0.0")
        serve(p.parse_args(sys.argv[2:]))
        return
    p = argparse.ArgumentParser(description="Make a Craft web release installable and usable offline.")
    p.add_argument("site", help="folder that holds the app's index.html")
    p.add_argument("--name", help="app name (default: the page title)")
    p.add_argument("--short-name", help="name under the home-screen icon (default: the name)")
    p.add_argument("--display", choices=["fullscreen", "standalone", "minimal-ui"], default="fullscreen",
                   help="fullscreen hides Android's status and navigation bars for more workspace (default)")
    p.add_argument("--icon", help="your own square PNG icon instead of the generated letter icon")
    p.add_argument("--color", default="#262626", help="splash and title-bar colour (default: the app's #262626)")
    build(p.parse_args())


if __name__ == "__main__":
    main()
