"""Climate operations: status, settings, set (read-modify-write), on/off."""

from __future__ import annotations

from typing import Any

from tyta.core.client import ToyotaClient

# ---------------------------------------------------------------------------
# Endpoint constants
# ---------------------------------------------------------------------------

VEHICLE_CLIMATE_STATUS_ENDPOINT = "/v1/global/remote/climate-status"
VEHICLE_CLIMATE_SETTINGS_ENDPOINT = "/v1/global/remote/climate-settings"
VEHICLE_CLIMATE_CONTROL_ENDPOINT = "/v1/global/remote/climate-control"


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------


async def get_climate_status(client: ToyotaClient, vin: str) -> dict[str, Any] | None:
    """Fetch the current climate control status.

    Args:
        client: Authenticated ToyotaClient instance.
        vin: Vehicle Identification Number.

    Returns:
        The ``payload`` sub-dict from the climate status API response,
        or ``None`` if the endpoint returned no payload.

    Raises:
        ToyotaApiError: If the API call returns a non-2xx response.

    """
    raw = await client.get(VEHICLE_CLIMATE_STATUS_ENDPOINT, vin=vin)
    return raw.get("payload")


async def get_climate_settings(client: ToyotaClient, vin: str) -> dict[str, Any] | None:
    """Fetch the current climate control settings.

    Args:
        client: Authenticated ToyotaClient instance.
        vin: Vehicle Identification Number.

    Returns:
        The ``payload`` sub-dict from the climate settings API response,
        or ``None`` if the endpoint returned no payload.

    Raises:
        ToyotaApiError: If the API call returns a non-2xx response.

    """
    raw = await client.get(VEHICLE_CLIMATE_SETTINGS_ENDPOINT, vin=vin)
    return raw.get("payload")


async def update_climate_settings(
    client: ToyotaClient,
    vin: str,
    temperature: float | None = None,
    unit: str | None = None,
    settings_on: bool | None = None,
) -> dict[str, Any]:
    """Update climate settings using read-modify-write.

    Fetches the current settings, applies only the provided overrides,
    then PUTs the full updated payload back to the API.

    Args:
        client: Authenticated ToyotaClient instance.
        vin: Vehicle Identification Number.
        temperature: New target temperature, or None to leave unchanged.
        unit: Temperature unit ("C" or "F"), or None to leave unchanged.
        settings_on: Whether climate settings should be on/off,
                     or None to leave unchanged.

    Returns:
        Dict with ``status`` and ``message`` indicating the update was sent.

    Raises:
        ToyotaApiError: If any API call returns a non-2xx response.

    """
    raw = await client.get(VEHICLE_CLIMATE_SETTINGS_ENDPOINT, vin=vin)
    current_payload = raw.get("payload") or {}

    # Apply overrides
    if temperature is not None:
        current_payload["temperature"] = temperature
    if unit is not None:
        current_payload["temperatureUnit"] = unit
    if settings_on is not None:
        current_payload["settingsOn"] = settings_on

    await client.put(VEHICLE_CLIMATE_SETTINGS_ENDPOINT, vin=vin, body=current_payload)
    return {
        "status": "command_queued",
        "message": "Climate settings updated. The vehicle may take a moment to respond.",
    }


async def send_climate_on(client: ToyotaClient, vin: str) -> dict[str, Any]:
    """Send a climate control start command to the vehicle.

    Args:
        client: Authenticated ToyotaClient instance.
        vin: Vehicle Identification Number.

    Returns:
        Dict with ``status`` and ``message`` indicating the command was queued.

    Raises:
        ToyotaApiError: If the API call returns a non-2xx response.

    """
    body = {"command": "start"}
    await client.post(VEHICLE_CLIMATE_CONTROL_ENDPOINT, vin=vin, body=body)
    return {
        "status": "command_queued",
        "message": "Climate on command sent. The vehicle may take a moment to respond.",
    }


async def send_climate_off(client: ToyotaClient, vin: str) -> dict[str, Any]:
    """Send a climate control stop command to the vehicle.

    Args:
        client: Authenticated ToyotaClient instance.
        vin: Vehicle Identification Number.

    Returns:
        Dict with ``status`` and ``message`` indicating the command was queued.

    Raises:
        ToyotaApiError: If the API call returns a non-2xx response.

    """
    body = {"command": "stop"}
    await client.post(VEHICLE_CLIMATE_CONTROL_ENDPOINT, vin=vin, body=body)
    return {
        "status": "command_queued",
        "message": "Climate off command sent. The vehicle may take a moment to respond.",
    }
