#!/usr/bin/env python3
"""serve.py — the dev server, with caching turned OFF.

`python3 -m http.server` sends `Last-Modified` and no `Cache-Control`, so a
browser is free to reuse a module it already has. For a page built out of ES
modules that is not a small annoyance: the page's module graph is fetched
through the HTTP cache, and `fetch(url, {cache: 'reload'})` from a console
does NOT reliably refresh it. The symptom is a page that fails to initialise
against a file on disk that is plainly correct, with a stale error in the
console pointing at an export that exists.

It has cost this project time more than once. HANDOFF's section 8 records the
same trap under "the previews do not render", where half an hour went into a
cached `info.js`.

    python3 serve.py [port] [--dir DIR]
"""
import argparse
import functools
import http.server
import os


class NoCacheHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Cache-Control', 'no-store, must-revalidate')
        self.send_header('Pragma', 'no-cache')
        self.send_header('Expires', '0')
        super().end_headers()

    # Quieter: one line per request is noise when a page pulls forty modules.
    def log_message(self, fmt, *args):
        if not str(args[1] if len(args) > 1 else '').startswith('2'):
            super().log_message(fmt, *args)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('port', nargs='?', type=int, default=8777)
    ap.add_argument('--dir', default=os.path.dirname(os.path.abspath(__file__)))
    a = ap.parse_args()
    handler = functools.partial(NoCacheHandler, directory=a.dir)
    with http.server.ThreadingHTTPServer(('', a.port), handler) as httpd:
        print(f'serving {a.dir} on http://localhost:{a.port}/  (no-store)')
        httpd.serve_forever()


if __name__ == '__main__':
    main()
