import click

from n6k_server.build.run import _config_fn
from nextpy_server.cli import (
    APP_DIR,
    _init,
    _run_build,
)


@click.group()
@click.option("--debug", is_flag=True, help="Enable debug logging.")
def cli(debug: bool):
    if debug:
        import os

        os.environ["N6K_DEBUG"] = "1"


@cli.command()
def build():
    """Discover app, write config, and build CSS/JS.

    Discovers from src/app/. Requires init to have been run first.
    """
    from n6k_server.discover import discover_app

    _run_build(discover_fn=discover_app, config_fn=_config_fn)


@cli.command()
@click.option("--host", default="127.0.0.1", help="Bind host.")
@click.option("--port", default=8000, type=int, help="Bind port.")
@click.option("--log-level", default="info", type=click.Choice(["debug", "info", "warning", "error", "critical"]), help="Log level.")
def dev(host: str, port: int, log_level: str):
    """Init then start uvicorn with --reload and live browser refresh."""
    import os
    import uvicorn

    _init()

    os.environ["N6K_DEV"] = "1"
    click.echo("Starting dev server (live reload)...")

    app_dir = str(APP_DIR.resolve())
    os.environ["N6K_APP_DIR"] = app_dir
    uvicorn.run(
        "n6k_server._dir_app:app",
        host=host,
        port=port,
        log_level=log_level,
        reload=True,
        reload_dirs=["src", app_dir],
        reload_includes=["*.py"],
        timeout_graceful_shutdown=1,
    )


@cli.command()
@click.option("--host", default="0.0.0.0", help="Bind host.")
@click.option("--port", default=8000, type=int, help="Bind port.")
@click.option("--workers", default=1, type=int, help="Number of worker processes.")
@click.option("--log-level", default="info", type=click.Choice(["debug", "info", "warning", "error", "critical"]), help="Log level.")
def serve(host: str, port: int, workers: int, log_level: str):
    """Start uvicorn for production (no build, no reload)."""
    import os
    import uvicorn

    click.echo("Starting server...")

    app_dir = str(APP_DIR.resolve())
    os.environ["N6K_APP_DIR"] = app_dir
    uvicorn.run(
        "n6k_server._dir_app:app",
        host=host,
        port=port,
        workers=workers,
        log_level=log_level,
    )
