"""Base models, enums, and validators for Medelement MIS API."""

from enum import IntEnum
from typing import Annotated
import re

from pydantic import BaseModel, ConfigDict, Field


class Gender(IntEnum):
    """Gender codes used in Medelement API."""

    FEMALE = 1
    MALE = 2


class ColorCode(IntEnum):
    """Color codes for reception highlighting (0-9)."""

    NONE = 0
    RED = 1
    GREEN = 2
    LIGHT_BLUE = 3
    YELLOW = 4
    PURPLE = 5
    ORANGE = 6
    GRAY = 7
    BROWN = 8
    DARK_TURQUOISE = 9


class ActiveStatus(IntEnum):
    """Reception active status."""

    CLOSED = 0
    OPEN = 1


class RemovedStatus(IntEnum):
    """Record removal status."""

    NOT_REMOVED = 0
    REMOVED = 1


class NomenclatureType(IntEnum):
    """Nomenclature item type."""

    SERVICE = 0
    CATEGORY = 1


# Type aliases
PhoneArray = list[str]
"""Phone as [country_code, city_code, phone_number]."""

SmallInt = Annotated[int, Field(ge=0, le=9)]
"""Small integer for color codes (0-9)."""


# Date/time format patterns
DATE_PATTERN = re.compile(r"^\d{2}\.\d{2}\.\d{4}$")
DATETIME_PATTERN = re.compile(r"^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}(:\d{2})?$")


def validate_date_format(value: str | None) -> str | None:
    """Validate date string is in dd.mm.yyyy format."""
    if value is None:
        return None
    if not DATE_PATTERN.match(value):
        raise ValueError("Date must be in dd.mm.yyyy format")
    return value


def validate_datetime_format(value: str | None) -> str | None:
    """Validate datetime string is in dd.mm.yyyy hh:mm format."""
    if value is None:
        return None
    if not DATETIME_PATTERN.match(value):
        raise ValueError("Datetime must be in dd.mm.yyyy hh:mm or dd.mm.yyyy hh:mm:ss format")
    return value


class MedelementBaseModel(BaseModel):
    """Base model with common configuration for all Medelement models."""

    model_config = ConfigDict(
        populate_by_name=True,
        str_strip_whitespace=True,
        validate_assignment=True,
    )
