"""Entry point for ``python -m cyclone``.

* ``python -m cyclone`` (no args) — Click CLI (``cli.main``)
* ``python -m cyclone serve``     — start the FastAPI app on 0.0.0.0:8000

Honors the env vars:

* ``CYCLONE_HOST`` (default ``0.0.0.0`` — always bind to all interfaces)
* ``CYCLONE_PORT`` (default ``8000``)
* ``CYCLONE_RELOAD`` (default ``0``; set to ``1`` to enable uvicorn reload)
"""

from __future__ import annotations

import os
import sys


def main() -> None:
    # Always run first-admin bootstrap before any other entry path.
    # Must happen before ``serve`` (uvicorn) AND before the Click CLI
    # dispatch — otherwise `python -m cyclone users create ...` on a
    # fresh DB would race with the bootstrap's check, and the API
    # could come up with zero users.
    from cyclone.auth import bootstrap
    bootstrap.run()

    # SP24: if the AUTH_DISABLED escape hatch is on, scream at boot so a
    # misconfigured production deploy fails loudly. The flag is flipped by
    # ``CYCLONE_AUTH_DISABLED=1`` (see ``cyclone.auth.bootstrap``) and by the
    # pytest conftest autouse fixture (see ``.superpowers/skills/cyclone-tests``).
    from cyclone.auth import deps as _auth_deps

    if _auth_deps.AUTH_DISABLED:
        import logging

        logging.getLogger("cyclone").warning(
            "AUTH_DISABLED is set (CYCLONE_AUTH_DISABLED=1) — all requests "
            "treated as admin, dev only. Do NOT enable this in production."
        )

    if len(sys.argv) >= 2 and sys.argv[1] == "serve":
        port = os.environ.get("CYCLONE_PORT", "8000")
        # Always bind to 0.0.0.0 so the API is reachable from the
        # frontend container on the compose bridge network AND from
        # the host (Vite dev proxy) AND from the LAN. Network isolation
        # is provided by the host firewall / compose port publishing,
        # not by binding to loopback. Override with CYCLONE_HOST if you
        # have a reason to restrict.
        host = os.environ.get("CYCLONE_HOST", "0.0.0.0")
        reload = os.environ.get("CYCLONE_RELOAD", "0") == "1"
        sys.argv = [
            sys.argv[0],
            "cyclone.api:app",
            "--host", host,
            "--port", port,
        ]
        if reload:
            sys.argv.append("--reload")
        # DB + EventBus are initialized by the FastAPI lifespan handler
        # (cyclone.api:lifespan); no explicit pre-init is needed here.
        import uvicorn

        uvicorn.main()
        return
    from cyclone.cli import main as cli_main

    cli_main()


if __name__ == "__main__":
    main()
