"""MCP server setup, tool registration, and entry point."""

from __future__ import annotations

import sys
from typing import Any

try:
    from mcp.server.fastmcp import FastMCP
except ImportError:
    print(
        "tyta-mcp requires the mcp extras. Install with: pip install tyta[mcp]",
        file=sys.stderr,
    )
    sys.exit(1)

from tyta.mcp.tools import (
    tool_auth_status,
    tool_climate_status,
    tool_electric_status,
    tool_health,
    tool_location,
    tool_remote_find,
    tool_remote_horn,
    tool_remote_lock,
    tool_remote_status,
    tool_remote_unlock,
    tool_telemetry,
    tool_trips_list,
    tool_trips_show,
    tool_vehicles_list,
)

# ---------------------------------------------------------------------------
# Server instance
# ---------------------------------------------------------------------------

mcp = FastMCP(
    name="tyta",
    instructions=(
        "tyta-mcp exposes Toyota Connected Services operations as MCP tools. "
        "Authentication is resolved automatically: if TOYOTA_USERNAME and TOYOTA_PASSWORD "
        "environment variables are set, the server will authenticate on the first tool call. "
        "Alternatively, run `tyta auth login` beforehand to store a token. "
        "Write operations (remote_lock, remote_unlock, remote_horn, remote_find) "
        "require confirm=True to prevent accidental execution."
    ),
)

# ---------------------------------------------------------------------------
# Tool registration
# ---------------------------------------------------------------------------


@mcp.tool(description="Check authentication status and token expiry.")
def auth_status() -> dict[str, Any]:
    """Return current authentication status."""
    return tool_auth_status()


@mcp.tool(description="List all vehicles linked to the Toyota account.")
async def vehicles_list() -> list[dict[str, Any]]:
    """List account vehicles."""
    return await tool_vehicles_list()


@mcp.tool(description="Fetch telemetry: fuel level, odometer, 12V battery.")
async def telemetry(vin: str | None = None) -> dict[str, Any] | None:
    """Fuel level, odometer, 12V battery status.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.

    """
    return await tool_telemetry(vin=vin)


@mcp.tool(description="Fetch GPS location: coordinates and timestamp.")
async def location(vin: str | None = None) -> dict[str, Any] | None:
    """GPS coordinates and last-seen timestamp.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.

    """
    return await tool_location(vin=vin)


@mcp.tool(description="Fetch remote/lock status: lock state and caution count.")
async def remote_status(vin: str | None = None) -> dict[str, Any] | None:
    """Door lock status and caution indicator count.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.

    """
    return await tool_remote_status(vin=vin)


@mcp.tool(description="Fetch vehicle health: warning lights and health alerts.")
async def health(vin: str | None = None) -> dict[str, Any] | None:
    """Warning lights and health alert status.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.

    """
    return await tool_health(vin=vin)


@mcp.tool(description="Fetch EV status: battery level, charging status, range.")
async def electric_status(vin: str | None = None) -> dict[str, Any] | None:
    """EV battery level, charging status, and estimated range.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.

    """
    return await tool_electric_status(vin=vin)


@mcp.tool(description="Fetch climate status: on/off, temperature, defoggers.")
async def climate_status(vin: str | None = None) -> dict[str, Any] | None:
    """Climate control on/off state, target temperature, and defogger status.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.

    """
    return await tool_climate_status(vin=vin)


@mcp.tool(description="Fetch trip history with optional date range.")
async def trips_list(
    vin: str | None = None,
    from_date: str | None = None,
    to_date: str | None = None,
    limit: int = 10,
    page: int = 1,
) -> dict[str, Any]:
    """Trip history list.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.
        from_date: Start date (YYYY-MM-DD). Defaults to 30 days ago.
        to_date: End date (YYYY-MM-DD). Defaults to today.
        limit: Maximum trips to return (1-50, default 10).
        page: 1-based page number (default 1).

    """
    return await tool_trips_list(
        vin=vin, from_date=from_date, to_date=to_date, limit=limit, page=page
    )


@mcp.tool(description="Fetch full detail for a single trip by ID.")
async def trips_show(trip_id: str, vin: str | None = None) -> dict[str, Any]:
    """Full trip detail including route waypoints.

    Args:
        trip_id: UUID string of the trip.
        vin: Vehicle VIN. Resolved via 4-step order if omitted.

    """
    return await tool_trips_show(trip_id=trip_id, vin=vin)


@mcp.tool(
    description=(
        "Lock vehicle doors. WRITE OPERATION — requires confirm=True to execute. "
        "This sends a command to a physical vehicle."
    )
)
async def remote_lock(vin: str | None = None, confirm: bool = False) -> dict[str, Any]:
    """Send door-lock command to the vehicle.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.
        confirm: Must be True to execute. Safety guard against accidental writes.

    """
    return await tool_remote_lock(vin=vin, confirm=confirm)


@mcp.tool(
    description=(
        "Unlock vehicle doors. WRITE OPERATION — requires confirm=True to execute. "
        "This sends a command to a physical vehicle."
    )
)
async def remote_unlock(vin: str | None = None, confirm: bool = False) -> dict[str, Any]:
    """Send door-unlock command to the vehicle.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.
        confirm: Must be True to execute. Safety guard against accidental writes.

    """
    return await tool_remote_unlock(vin=vin, confirm=confirm)


@mcp.tool(
    description=(
        "Sound the vehicle horn. WRITE OPERATION — requires confirm=True to execute. "
        "This sends a command to a physical vehicle."
    )
)
async def remote_horn(vin: str | None = None, confirm: bool = False) -> dict[str, Any]:
    """Send sound-horn command to the vehicle.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.
        confirm: Must be True to execute. Safety guard against accidental writes.

    """
    return await tool_remote_horn(vin=vin, confirm=confirm)


@mcp.tool(
    description=(
        "Flash lights and sound horn to locate the vehicle. "
        "WRITE OPERATION — requires confirm=True to execute. "
        "This sends a command to a physical vehicle."
    )
)
async def remote_find(vin: str | None = None, confirm: bool = False) -> dict[str, Any]:
    """Send find-vehicle command (flash lights + horn) to the vehicle.

    Args:
        vin: Vehicle VIN. Resolved via 4-step order if omitted.
        confirm: Must be True to execute. Safety guard against accidental writes.

    """
    return await tool_remote_find(vin=vin, confirm=confirm)


# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------


def main() -> None:
    """Start the tyta MCP server over stdio transport."""
    mcp.run(transport="stdio")
