"""tyta climate subcommands: status, settings, set, on, off."""

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 climate as core_climate
from tyta.core import config as core_config
from tyta.core import envelope as env
from tyta.core import vehicles as core_vehicles
from tyta.core.client import ToyotaApiError, ToyotaClient

app = typer.Typer(
    name="climate",
    help="Climate control commands.",
    no_args_is_help=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 _build_client_and_vin(
    vin_flag: str | None,
    state: dict,
) -> tuple[ToyotaClient, str, list[str]] | None:
    """Resolve auth, build client, and resolve VIN. Returns None and emits error on failure."""
    debug = state.get("debug", False)
    auth_path = core_auth.get_auth_path(state.get("auth_file"))
    config_path = state.get("config_file")

    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.command("status")
def climate_status(
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Show the current climate control status."""
    asyncio.run(_climate_status(vin))


async def _climate_status(vin_flag: str | None) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    result = await _build_client_and_vin(vin_flag, state)
    if result is None:
        return
    client, vin, warnings = result

    try:
        data = await core_climate.get_climate_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, "climate_status": data}, warnings=warnings), command="climate status"
    )


@app.command("settings")
def climate_settings(
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Show the current climate control settings."""
    asyncio.run(_climate_settings(vin))


async def _climate_settings(vin_flag: str | None) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    result = await _build_client_and_vin(vin_flag, state)
    if result is None:
        return
    client, vin, warnings = result

    try:
        data = await core_climate.get_climate_settings(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, "climate_settings": data}, warnings=warnings),
        command="climate settings",
    )


@app.command("set")
def climate_set(
    temperature: Annotated[
        float | None,
        typer.Option("--temperature", help="Target temperature (float)."),
    ] = None,
    unit: Annotated[
        str | None,
        typer.Option("--unit", help="Temperature unit: C or F."),
    ] = None,
    on: Annotated[
        bool,
        typer.Option("--on/", help="Turn climate settings on.", is_flag=True),
    ] = False,
    off: Annotated[
        bool,
        typer.Option("--off/", help="Turn climate settings off.", is_flag=True),
    ] = False,
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Update climate settings (read-modify-write).

    At least one of --temperature, --unit, --on, or --off must be provided.
    --on and --off are mutually exclusive.
    """
    if on and off:
        typer.echo(
            "Error: --on and --off are mutually exclusive. Provide at most one.",
            err=True,
        )
        raise typer.Exit(code=2)

    settings_on: bool | None = None
    if on:
        settings_on = True
    elif off:
        settings_on = False

    asyncio.run(_climate_set(vin, temperature, unit, settings_on))


async def _climate_set(
    vin_flag: str | None,
    temperature: float | None,
    unit: str | None,
    settings_on: bool | None,
) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    result = await _build_client_and_vin(vin_flag, state)
    if result is None:
        return
    client, vin, warnings = result

    try:
        data = await core_climate.update_climate_settings(
            client,
            vin,
            temperature=temperature,
            unit=unit,
            settings_on=settings_on,
        )
    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, **data}, warnings=warnings), command="climate set")


@app.command("on")
def climate_on(
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Start climate control on the vehicle."""
    asyncio.run(_climate_on(vin))


async def _climate_on(vin_flag: str | None) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    result = await _build_client_and_vin(vin_flag, state)
    if result is None:
        return
    client, vin, warnings = result

    try:
        data = await core_climate.send_climate_on(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, **data}, warnings=warnings), command="climate on")


@app.command("off")
def climate_off(
    vin: Annotated[
        str | None,
        typer.Option("--vin", help="VIN of the vehicle to query.", show_default=False),
    ] = None,
) -> None:
    """Stop climate control on the vehicle."""
    asyncio.run(_climate_off(vin))


async def _climate_off(vin_flag: str | None) -> None:
    state = _get_state()
    debug = state.get("debug", False)
    result = await _build_client_and_vin(vin_flag, state)
    if result is None:
        return
    client, vin, warnings = result

    try:
        data = await core_climate.send_climate_off(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, **data}, warnings=warnings), command="climate off")
