from __future__ import annotations

from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from functools import partial
from pathlib import Path
import sys


ROOT = Path(__file__).resolve().parent


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


if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8765
    # Bind address is optional and defaults to loopback so nothing is exposed unless
    # asked for. Pass "0.0.0.0" to also serve the Tailscale / LAN interfaces, which is
    # what makes the dashboard reachable from other devices without a tunnel.
    host = sys.argv[2] if len(sys.argv) > 2 else "127.0.0.1"
    handler = partial(NoCacheHandler, directory=str(ROOT))
    server = ThreadingHTTPServer((host, port), handler)
    shown = "127.0.0.1" if host in ("0.0.0.0", "::") else host
    print(f"研究看板：http://{shown}:{port}/reports/dashboard/index.html")
    if host in ("0.0.0.0", "::"):
        print("（已监听所有网卡：本机回环、局域网、Tailscale 均可访问）")
    server.serve_forever()
