#!/usr/bin/env python3
"""
Minimal static server for the iOS Translate isolated-world POC.

Service Workers require a secure context. Options:

  * Plain HTTP on localhost (default):
        python3 server.py
    Then reach it from the iOS device as `http://localhost:8080/poc.html`
    via USB port-forwarding (e.g. `iproxy 8080 8080`) — `localhost` is a
    secure context, so SW registration succeeds.

  * HTTPS for LAN / public testing:
        python3 server.py --https --cert cert.pem --key key.pem --port 8443
    The certificate must be trusted by the iOS device (install the CA in
    Settings → General → About → Certificate Trust Settings), otherwise
    WKWebView refuses to register the Service Worker.
"""

import argparse
import http.server
import os
import ssl
import sys


class Handler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        # Ensure the SW script is never cached during iteration.
        self.send_header("Cache-Control", "no-store")
        # Correct MIME for sw.js (SimpleHTTPRequestHandler usually gets
        # this right, but be explicit for safety).
        if self.path.endswith(".js"):
            self.send_header("Service-Worker-Allowed", "/")
        super().end_headers()

    def log_message(self, fmt, *args):
        sys.stderr.write("[server] %s - %s\n" %
                         (self.client_address[0], fmt % args))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=8080)
    ap.add_argument("--bind", default="0.0.0.0")
    ap.add_argument("--https", action="store_true")
    ap.add_argument("--cert", default="cert.pem")
    ap.add_argument("--key", default="key.pem")
    args = ap.parse_args()

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    httpd = http.server.ThreadingHTTPServer((args.bind, args.port), Handler)
    scheme = "http"
    if args.https:
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        ctx.load_cert_chain(certfile=args.cert, keyfile=args.key)
        httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
        scheme = "https"

    print(f"[server] serving {os.getcwd()} at "
          f"{scheme}://{args.bind}:{args.port}/poc.html")
    print("[server] Service Workers need a secure context: use localhost "
          "or a trusted HTTPS cert.")
    httpd.serve_forever()


if __name__ == "__main__":
    main()
