"""tyta status, tyta telemetry, and tyta health commands."""

from __future__ import annotations

import asyncio
import json
import sys
from typing import Annotated

import typer

from tyta.cli import render
from tyta.core import auth as core_auth
from tyta.core import config as core_config
from tyta.core import envelope as env
from tyta.core import status as core_status
from tyta.core import vehicles as core_vehicles
from tyta.core.client import ToyotaApiError, ToyotaClient

app = typer.Typer(
    name="status",
    help="Show vehicle status.",
    no_args_is_help=False,
    invoke_without_command=True,
)

telemetry_app = typer.Typer(
    name="telemetry",
    help="Show raw telemetry (fuel, odometer, battery).",
    no_args_is_help=False,
    invoke_without_command=True,
)

health_app = typer.Typer(
    name="health",
    help="Show vehicle health (warning lights, alerts).",
    no_args_is_help=False,
    invoke_without_command=True,
)


def _get_state() -> dict:
    from tyta.cli.main import _get_state as _gs

    return _gs()


def _is_json_mode() -> bool:
    return _get_state().get("json", False)


def _load_config() -> dict:
    config_path = core_config.get_config_path(_get_state().get("config_file"))
    try:
        return core_config.load_config(config_path)
    except Exception:  # noqa: BLE001
        return {}


def _emit_and_exit(data: dict, exit_code: int = 0, command: str = "") -> None:
    json_mode = _is_json_mode()
    if exit_code != 0:
        render.render_error(data, json_mode)
    else:
        render.render_output(data, json_mode, command, config=_load_config())
    sys.exit(exit_code)


async def _resolve_client_and_vin(
    vin_flag: str | None, debug: bool, auth_path: str, config_path: str | None
) -> tuple[ToyotaClient, str, list[str]] | None:
    """Shared helper: authenticate, create client, resolve VIN.

    Returns (client, vin, warnings) tuple or None on error (after emitting).
    """
    try:
        token_data = await core_auth.get_valid_token(auth_path)
    except core_auth.NotAuthenticatedError as exc:
        _emit_and_exit(env.error(exc.code, exc.message), exit_code=1)
        return None
    except core_auth.TokenExpiredError as exc:
        _emit_and_exit(env.error(exc.code, exc.message), exit_code=1)
        return None
    except json.JSONDecodeError:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("invalid_config", "Token file is malformed JSON."), exit_code=1)
        return None

    client = ToyotaClient(
        access_token=token_data["access_token"],
        uuid=token_data["uuid"],
    )

    try:
        vin, warnings = await core_vehicles.resolve_vin(
            client, vin_flag=vin_flag, config_path=config_path
        )
    except core_vehicles.NoVehiclesError as exc:
        _emit_and_exit(env.error(exc.code, exc.message), exit_code=1)
        return None
    except core_vehicles.VehicleNotFoundError as exc:
        _emit_and_exit(env.error(exc.code, exc.message), exit_code=1)
        return None
    except ToyotaApiError as exc:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("api_error", f"Toyota API error: {exc.message}"), exit_code=1)
        return None

    return client, vin, warnings


@app.callback(invoke_without_command=True)
def status_command(
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Show dashboard, location, lock status, and health for a vehicle."""
    asyncio.run(_status(vin))


async def _status(vin_flag: str | None) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    auth_path = core_auth.get_auth_path(state.get("auth_file"))
    config_path = state.get("config_file")

    result = await _resolve_client_and_vin(vin_flag, debug, auth_path, config_path)
    if result is None:
        return
    client, vin, warnings = result

    try:
        status_data = await core_status.get_status(client, vin)
    except ToyotaApiError as exc:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("api_error", f"Toyota API error: {exc.message}"), exit_code=1)
        return
    except Exception as exc:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("unknown_error", str(exc)), exit_code=1)
        return

    _emit_and_exit(env.ok({"vin": vin, **status_data}, warnings=warnings), command="status")


# ---------------------------------------------------------------------------
# tyta telemetry
# ---------------------------------------------------------------------------


@telemetry_app.callback(invoke_without_command=True)
def telemetry_command(
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Show raw telemetry: fuel level, odometer, battery."""
    asyncio.run(_telemetry(vin))


async def _telemetry(vin_flag: str | None) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    auth_path = core_auth.get_auth_path(state.get("auth_file"))
    config_path = state.get("config_file")

    result = await _resolve_client_and_vin(vin_flag, debug, auth_path, config_path)
    if result is None:
        return
    client, vin, warnings = result

    try:
        payload = await core_status.get_telemetry(client, vin)
    except ToyotaApiError as exc:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("api_error", f"Toyota API error: {exc.message}"), exit_code=1)
        return
    except Exception as exc:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("unknown_error", str(exc)), exit_code=1)
        return

    _emit_and_exit(
        env.ok({"vin": vin, "telemetry": payload}, warnings=warnings), command="telemetry"
    )


# ---------------------------------------------------------------------------
# tyta health
# ---------------------------------------------------------------------------


@health_app.callback(invoke_without_command=True)
def health_command(
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Show vehicle health: warning lights and alerts."""
    asyncio.run(_health(vin))


async def _health(vin_flag: str | None) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    auth_path = core_auth.get_auth_path(state.get("auth_file"))
    config_path = state.get("config_file")

    result = await _resolve_client_and_vin(vin_flag, debug, auth_path, config_path)
    if result is None:
        return
    client, vin, warnings = result

    try:
        payload = await core_status.get_health(client, vin)
    except ToyotaApiError as exc:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("api_error", f"Toyota API error: {exc.message}"), exit_code=1)
        return
    except Exception as exc:
        if debug:
            import traceback

            traceback.print_exc(file=sys.stderr)
        _emit_and_exit(env.error("unknown_error", str(exc)), exit_code=1)
        return

    _emit_and_exit(env.ok({"vin": vin, "health": payload}, warnings=warnings), command="health")
