#!/usr/bin/env python3
"""Serve the PWA on http://localhost:8080/.

PWAs are installable from localhost without HTTPS, so plain HTTP is fine
for local reproduction. Generates placeholder icons on first run so the
manifest is installable.
"""
import http.server
import os
import socketserver
import struct
import zlib

ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pwa")
PORT = 8080


def _png(size: int) -> bytes:
    """Return a minimal solid-grey size×size PNG."""
    def chunk(tag: bytes, data: bytes) -> bytes:
        return (struct.pack(">I", len(data)) + tag + data +
                struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
    sig = b"\x89PNG\r\n\x1a\n"
    ihdr = chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0))
    raw = b"".join(b"\x00" + b"\x40\x40\x40" * size for _ in range(size))
    idat = chunk(b"IDAT", zlib.compress(raw, 9))
    iend = chunk(b"IEND", b"")
    return sig + ihdr + idat + iend


def ensure_icons() -> None:
    for sz in (192, 512):
        p = os.path.join(ROOT, f"icon-{sz}.png")
        if not os.path.exists(p):
            with open(p, "wb") as f:
                f.write(_png(sz))


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=ROOT, **kw)

    def end_headers(self):
        self.send_header("Cache-Control", "no-store")
        if self.path.endswith("manifest.json"):
            self.send_header("Content-Type", "application/manifest+json")
        super().end_headers()


if __name__ == "__main__":
    ensure_icons()
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("127.0.0.1", PORT), Handler) as httpd:
        print(f"Serving PWA at http://localhost:{PORT}/index.html")
        httpd.serve_forever()
