from __future__ import annotations

import json
import sys
from pathlib import Path

import uvicorn

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
  sys.path.insert(0, str(PROJECT_ROOT))


def _read_port_from_config() -> int:
  cfg_path = PROJECT_ROOT / "api" / "data" / "config.json"
  if not cfg_path.exists():
    return 8008
  try:
    data = json.loads(cfg_path.read_text(encoding="utf-8"))
    value = data.get("api_port", 8008)
    port = int(value)
    return port if 1 <= port <= 65535 else 8008
  except Exception:
    return 8008


def main() -> None:
  port = _read_port_from_config()
  uvicorn.run("api.app.main:app", host="0.0.0.0", port=port, reload=False)


if __name__ == "__main__":
  main()
