import http.server
import os
import socketserver
import subprocess
import sys


def main() -> int:
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    docs_dir = os.path.join(root, "docs")
    build_dir = os.path.join(docs_dir, "_build", "html")

    cmd = [
        sys.executable,
        "-m",
        "sphinx",
        "-b",
        "html",
        docs_dir,
        build_dir,
    ]
    print("Running:", " ".join(cmd))
    res = subprocess.run(cmd, check=False)
    if res.returncode != 0:
        return res.returncode

    port = int(os.environ.get("TOPOVEC_DOCS_PORT", "8000"))
    os.chdir(build_dir)
    handler = http.server.SimpleHTTPRequestHandler
    with socketserver.TCPServer(("", port), handler) as httpd:
        print(f"Serving docs at http://localhost:{port}/")
        print("Press Ctrl+C to stop.")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            return 0
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
