"""Lookups API endpoints for database-driven enumerations."""

from __future__ import annotations

from typing import TYPE_CHECKING

from vikdata.models.lookup import (
    Lookup,
    LookupCategory,
    LookupCreate,
    LookupsResponse,
    LookupUpdate,
)

if TYPE_CHECKING:
    from vikdata.client import VikdataClient


class LookupsAPI:
    """Lookups API endpoints.

    Handles fetching and managing database-driven lookup values.

    Lookup categories include:
    - vessel_type: fishing, cargo, tanker, passenger, research, tug, other
    - vessel_status: active, inactive, maintenance, decommissioned
    - ais_class: A, B
    - subscription_status: active, trialing, past_due, canceled, paused
    - invoice_status: draft, pending, paid, failed, void
    """

    def __init__(self, client: "VikdataClient") -> None:
        """Initialize lookups API.

        Args:
            client: VikdataClient instance
        """
        self._client = client

    async def get_all(self, include_inactive: bool = False) -> LookupsResponse:
        """Get all lookups grouped by category.

        Returns system-wide lookups plus any tenant-specific lookups
        for the authenticated user's tenant.

        Args:
            include_inactive: Whether to include inactive lookups (default: False)

        Returns:
            LookupsResponse with lookups grouped by category

        Raises:
            AuthenticationError: Not authenticated
        """
        params = {}
        if include_inactive:
            params["include_inactive"] = True
        return await self._client.request(
            "GET",
            "/api/v1/lookups",
            params=params if params else None,
            response_model=LookupsResponse,
        )

    async def get_categories(self) -> list[str]:
        """Get list of available lookup categories.

        Returns:
            List of category names

        Raises:
            AuthenticationError: Not authenticated
        """
        return await self._client.request(
            "GET",
            "/api/v1/lookups/categories",
        )

    async def get_category(
        self, category: str, include_inactive: bool = False
    ) -> LookupCategory:
        """Get lookups for a specific category.

        Args:
            category: Category name (e.g., 'vessel_type', 'vessel_status')
            include_inactive: Whether to include inactive lookups (default: False)

        Returns:
            LookupCategory with category name and lookup values

        Raises:
            AuthenticationError: Not authenticated
            ResourceNotFoundError: Category not found
        """
        params = {}
        if include_inactive:
            params["include_inactive"] = True
        return await self._client.request(
            "GET",
            f"/api/v1/lookups/{category}",
            params=params if params else None,
            response_model=LookupCategory,
        )

    async def create(self, category: str, data: LookupCreate) -> Lookup:
        """Create a tenant-specific lookup value.

        Tenants can add custom values to any category. These values
        are only visible to users within that tenant.

        Args:
            category: Category to add the lookup to
            data: Lookup data (slug, name, description, etc.)

        Returns:
            The created Lookup

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing permission to create lookups
            ValidationError: Invalid data (e.g., duplicate slug)
        """
        return await self._client.request(
            "POST",
            f"/api/v1/lookups/{category}",
            json=data,
            response_model=Lookup,
        )

    async def update(
        self, category: str, slug: str, data: LookupUpdate
    ) -> Lookup:
        """Update a tenant-specific lookup value.

        Only tenant-created lookups can be updated. System lookups
        cannot be modified.

        Args:
            category: Category the lookup belongs to
            slug: Slug of the lookup to update
            data: Update data (name, description, sort_order, is_active, metadata)

        Returns:
            The updated Lookup

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing permission or trying to modify system lookup
            ResourceNotFoundError: Lookup not found
        """
        return await self._client.request(
            "PATCH",
            f"/api/v1/lookups/{category}/{slug}",
            json=data,
            response_model=Lookup,
        )

    async def delete(self, category: str, slug: str) -> None:
        """Delete a tenant-specific lookup value.

        Only tenant-created lookups can be deleted. System lookups
        cannot be removed.

        Args:
            category: Category the lookup belongs to
            slug: Slug of the lookup to delete

        Raises:
            AuthenticationError: Not authenticated
            AuthorizationError: Missing permission or trying to delete system lookup
            ResourceNotFoundError: Lookup not found
        """
        await self._client.request(
            "DELETE",
            f"/api/v1/lookups/{category}/{slug}",
        )

    async def get_valid_slugs(self, category: str) -> list[str]:
        """Get list of valid slug values for a category.

        Convenience method that returns just the slugs from active lookups.
        Useful for validation.

        Args:
            category: Category name

        Returns:
            List of valid slug strings

        Raises:
            AuthenticationError: Not authenticated
            ResourceNotFoundError: Category not found
        """
        cat = await self.get_category(category, include_inactive=False)
        return [lookup.slug for lookup in cat.values if lookup.is_active]
