"""Nomenclature (service catalog) models for Medelement MIS API."""

from typing import Optional

from pydantic import Field, RootModel

from .base import MedelementBaseModel, NomenclatureType


class GetNomenclaturesRequest(MedelementBaseModel):
    """Request model for getting nomenclatures/services.

    GET https://api3.medelement.com/v1/doctor/nomenclatures
    """

    category_code: Optional[int] = Field(None, description="Filter by category code")
    skip: Optional[int] = Field(None, ge=0, description="Pagination offset")
    q: Optional[str] = Field(None, description="Search query string")


class Nomenclature(MedelementBaseModel):
    """Nomenclature/service catalog item.

    Represents a medical service or category in the service catalog.
    Uses UPPERCASE field names from API.
    """

    nomenclature_code: int = Field(..., alias="NOMENCLATURE_CODE")
    nomenclature_name: str = Field(..., alias="NOMENCLATURE_NAME")
    nomenclature_type_code: int = Field(..., alias="NOMENCLATURE_TYPE_CODE")
    is_group: int = Field(
        ..., alias="IS_GROUP", description="0=Service, 1=Category/Group"
    )
    reccount: Optional[int] = Field(
        None, alias="RECCOUNT", description="Total records count"
    )
    parent_code: Optional[int] = Field(
        None, alias="PARENT_CODE", description="Parent category code"
    )
    parent_name: Optional[str] = Field(
        None, alias="PARENT_NAME", description="Parent category name"
    )
    nesting_level: Optional[int] = Field(
        None, alias="NESTING_LEVEL", description="Tree depth level"
    )
    price: Optional[float] = Field(None, alias="PRICE", description="Service price")
    unit_name: Optional[str] = Field(
        None, alias="UNIT_NAME", description="Unit of measurement"
    )

    @property
    def is_category(self) -> bool:
        """Check if this nomenclature is a category (group)."""
        return self.is_group == NomenclatureType.CATEGORY

    @property
    def is_service(self) -> bool:
        """Check if this nomenclature is a service."""
        return self.is_group == NomenclatureType.SERVICE

    @property
    def has_parent(self) -> bool:
        """Check if this nomenclature has a parent category."""
        return self.parent_code is not None


class GetNomenclaturesResponse(RootModel[list[Nomenclature]]):
    """Response model for nomenclatures list.

    Returns array of nomenclature items.
    """

    def __iter__(self):
        return iter(self.root)

    def __getitem__(self, index):
        return self.root[index]

    def __len__(self):
        return len(self.root)

    @property
    def categories(self) -> list[Nomenclature]:
        """Get only category items."""
        return [n for n in self.root if n.is_category]

    @property
    def services(self) -> list[Nomenclature]:
        """Get only service items."""
        return [n for n in self.root if n.is_service]
