"""Trip history operations."""

from __future__ import annotations

from datetime import date, timedelta
from typing import Any

from tyta.core.client import ToyotaClient

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

VEHICLE_TRIPS_ENDPOINT = "/v1/trips"
VEHICLE_TRIP_DETAIL_ENDPOINT = "/v1/trips/{trip_id}"

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


async def list_trips(
    client: ToyotaClient,
    vin: str,
    from_date: date | None = None,
    to_date: date | None = None,
    route: bool = False,
    limit: int = 10,
    page: int = 1,
) -> dict[str, Any]:
    """Fetch trip history for a vehicle.

    Args:
        client: Authenticated ToyotaClient instance.
        vin: Vehicle Identification Number.
        from_date: Start date (inclusive). Defaults to today minus 30 days.
        to_date: End date (inclusive). Defaults to today.
        route: If True, include per-trip route geometry.
        limit: Maximum trips to return (default 10, max 50).
        page: 1-based page number (default 1).

    Returns:
        Raw trips response dict from the API.

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

    """
    today = date.today()
    if to_date is None:
        to_date = today
    if from_date is None:
        from_date = today - timedelta(days=30)

    # Clamp limit to allowed range
    limit = max(1, min(50, limit))
    offset = (max(1, page) - 1) * limit

    params: dict[str, Any] = {
        "from": from_date.isoformat(),
        "to": to_date.isoformat(),
        "route": str(route).lower(),
        "summary": "false",
        "limit": limit,
        "offset": offset,
    }
    return await client.get(VEHICLE_TRIPS_ENDPOINT, vin=vin, params=params)


async def get_trip(
    client: ToyotaClient,
    vin: str,
    trip_id: str,
) -> dict[str, Any]:
    """Fetch full detail for a single trip.

    Calls GET /v1/trips/{trip_id}. Route waypoints are always included.

    Args:
        client: Authenticated ToyotaClient instance.
        vin: Vehicle Identification Number.
        trip_id: UUID string of the trip.

    Returns:
        Raw trip detail response dict from the API (payload key contains trip data).

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

    """
    endpoint = VEHICLE_TRIP_DETAIL_ENDPOINT.format(trip_id=trip_id)
    return await client.get(endpoint, vin=vin)
