from __future__ import annotations

import argparse
import sys
from http.server import ThreadingHTTPServer
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser(description="Run an isolated preservation runtime")
    parser.add_argument("--runtime-root", type=Path, required=True)
    parser.add_argument("--data-dir", type=Path, required=True)
    parser.add_argument("--port", type=int, required=True)
    args = parser.parse_args()

    runtime_root = args.runtime_root.resolve()
    data_dir = args.data_dir.resolve()
    data_dir.mkdir(parents=True, exist_ok=True)
    sys.path.insert(0, str(runtime_root))

    if (runtime_root / "backend" / "bootstrap" / "config.py").is_file():
        from backend.bootstrap import config

        config.DATA_DIR = data_dir
        config.PRIVATE_MENTOR_SKILLS_DIR = data_dir / "private-mentor-skills"
    else:
        import app_config as config

        config.DATA_DIR = data_dir
        config.PRIVATE_MENTOR_SKILLS_DIR = data_dir / "private-mentor-skills"

    from server import RequestHandler, SERVICE

    server = ThreadingHTTPServer(("127.0.0.1", args.port), RequestHandler)
    try:
        if hasattr(SERVICE, "start_background_jobs"):
            SERVICE.start_background_jobs()
        print(
            f"Preservation runtime is running at http://127.0.0.1:{args.port} "
            f"with database {SERVICE.database.path}",
            flush=True,
        )
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        if hasattr(SERVICE, "stop_background_jobs"):
            SERVICE.stop_background_jobs()
        else:
            SERVICE._background_stop.set()
        server.server_close()


if __name__ == "__main__":
    main()
