#!/usr/bin/env python3
"""HTTP server for the COM1 PWA reserved-device-name POC.

Generates the required PWA icons on first run (so the manifest meets
installability criteria) and serves all files in this directory on
http://localhost:8080/.
"""
import http.server
import os
import socketserver
import struct
import zlib

HERE = os.path.dirname(os.path.abspath(__file__))
PORT = 8080


def _write_png(path: str, size: int) -> None:
    """Write a solid-red size x size PNG without external deps."""
    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'\xff\x00\x00' * size for _ in range(size))
    idat = chunk(b'IDAT', zlib.compress(raw, 9))
    iend = chunk(b'IEND', b'')
    with open(path, 'wb') as f:
        f.write(sig + ihdr + idat + iend)


def ensure_icons() -> None:
    for sz in (192, 512):
        p = os.path.join(HERE, f'icon-{sz}.png')
        if not os.path.exists(p):
            _write_png(p, sz)
            print(f'[+] generated {p}')


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

    def end_headers(self):
        # Service-Worker requires same-origin + correct MIME; also disable
        # caching so manifest edits (e.g. name -> "PRN") take effect.
        self.send_header('Cache-Control', 'no-store')
        self.send_header('Service-Worker-Allowed', '/')
        super().end_headers()


def main():
    ensure_icons()
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(('127.0.0.1', PORT), Handler) as httpd:
        print(f'[+] serving POC on http://localhost:{PORT}/poc.html')
        httpd.serve_forever()


if __name__ == '__main__':
    main()
