"""Root Typer app, global callback, top-level exception handler."""

from __future__ import annotations

import sys
from typing import Annotated

import typer
from loguru import logger

app = typer.Typer(
    name="toyota",
    help="Toyota Connected Services CLI.",
    no_args_is_help=True,
    add_completion=True,
)

# State object passed between callback and commands via typer context
_state: dict = {}


def _get_state() -> dict:
    return _state


@app.callback()
def main(
    ctx: typer.Context,
    debug: Annotated[bool, typer.Option("--debug", help="Enable debug logs to stderr.")] = False,
    auth_file: Annotated[
        str | None,
        typer.Option(
            "--auth-file",
            envvar="TOYOTA_AUTH_FILE",
            help="Path to auth token file.",
            show_default=False,
        ),
    ] = None,
    config_file: Annotated[
        str | None,
        typer.Option(
            "--config-file",
            envvar="TOYOTA_CONFIG_FILE",
            help="Path to config file.",
            show_default=False,
        ),
    ] = None,
    json_mode: Annotated[
        bool,
        typer.Option(
            "--json",
            "-j",
            help="Output raw JSON envelope instead of human-readable format.",
        ),
    ] = False,
) -> None:
    """Toyota Connected Services CLI."""
    # Always remove default loguru handler first to suppress output
    logger.remove()
    if debug:
        logger.add(sys.stderr, level="DEBUG")

    _state["debug"] = debug
    _state["auth_file"] = auth_file
    _state["config_file"] = config_file
    _state["json"] = json_mode


# Import and register sub-apps after defining the root app to avoid circular imports
def _register_subapps() -> None:
    from tyta.cli import auth as auth_cli
    from tyta.cli import climate as climate_cli
    from tyta.cli import config as config_cli
    from tyta.cli import electric as electric_cli
    from tyta.cli import location as location_cli
    from tyta.cli import remote as remote_cli
    from tyta.cli import status as status_cli
    from tyta.cli import trips as trips_cli
    from tyta.cli import vehicles as vehicles_cli

    app.add_typer(auth_cli.app, name="auth")
    app.add_typer(config_cli.app, name="config")
    app.add_typer(vehicles_cli.app, name="vehicles")
    app.add_typer(status_cli.app, name="status")
    app.add_typer(status_cli.telemetry_app, name="telemetry")
    app.add_typer(status_cli.health_app, name="health")
    app.add_typer(location_cli.app, name="location")
    app.add_typer(electric_cli.app, name="electric")
    app.add_typer(climate_cli.app, name="climate")
    app.add_typer(trips_cli.app, name="trips")
    app.add_typer(remote_cli.app, name="remote")


_register_subapps()
