#!/usr/bin/env python3
"""Serve an explainer-site directory over HTTP and remember the port.

    # launch it detached — proc("start") is the ONLY shape that works:
    r = await proc("start", "uv --project ~/.agents/skills/use-uv run python "
                            f"{__file__} /path/to/site")
    print(r.pid, r.log)
    port = open("/tmp/siteport.txt").read().strip()

    # later:
    await proc("kill", pid=r.pid)

This script stays in the FOREGROUND and does not daemonize itself. Detaching is
the launcher's job, and a script that forks internally is how the pipe trap gets
sprung: the forked child inherits the launcher's stdout, the write end of the
capture pipe never closes, and `subprocess.run(..., capture_output=True)` waits
for an EOF that will not arrive. `nohup` and `setsid` do not help — they change
signal disposition and session, not file descriptors. `proc("start", ...)`
points stdout at a log file instead of a pipe, which is the actual fix.

Port 0 means "pick a free one", which is what you want: a stale hardcoded port
silently serves the previous site, or nothing.
"""
import argparse, functools, http.server, socket, socketserver, sys
from pathlib import Path

DEFAULT_PORTFILE = "/tmp/siteport.txt"


def free_port():
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    p = s.getsockname()[1]
    s.close()
    return p


class Quiet(http.server.SimpleHTTPRequestHandler):
    def log_message(self, *a):
        pass


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("directory")
    ap.add_argument("--port", type=int, default=0)
    ap.add_argument("--portfile", default=DEFAULT_PORTFILE)
    a = ap.parse_args()

    root = Path(a.directory).resolve()
    if not (root / "index.html").exists():
        sys.exit(f"no index.html under {root}")

    port = a.port or free_port()
    handler = functools.partial(Quiet, directory=str(root))
    socketserver.TCPServer.allow_reuse_address = True
    httpd = socketserver.TCPServer(("127.0.0.1", port), handler)

    # Written before serving, so a launcher that polls for it sees the port the
    # moment the socket is bound — and bound happens in the foreground process,
    # not in a child nobody is watching.
    Path(a.portfile).write_text(str(port))
    print(f"http://127.0.0.1:{port}/index.html", flush=True)
    httpd.serve_forever()


if __name__ == "__main__":
    main()
