"""Test and subtest models for medical tests."""
from datetime import UTC, datetime
from functools import partial
from typing import Annotated, List, Optional

from pydantic import BaseModel, Field, StringConstraints, computed_field

from .base import BaseDocument
from .types import PyObjectId
class SubTest(BaseModel):
    """SubTest model representing subtests within a test."""
    name: Annotated[
        str, StringConstraints(min_length=1, strip_whitespace=True)
    ] = Field(description="Name of the subtest")
    value: Optional[float] = Field(
        default=None, description="Result value of the subtest"
    )
    unit: Optional[str] = Field(
        default=None, description="Unit of measurement"
    )
    refMin: Optional[float] = Field(
        default=None, description="Minimum value of normal reference range"
    )
    refMax: Optional[float] = Field(
        default=None, description="Maximum value of normal reference range"
    )

    @computed_field
    @property
    def status(self) -> str:
        """Compute status based on value and reference range."""
        if self.value is None:
            return "pending"

        if self.refMin is None or self.refMax is None:
            return "unknown"

        if self.value < self.refMin or self.value > self.refMax:
            return "abnormal"

        return "normal"
class Test(BaseDocument):
    """Test model representing medical tests."""
    testId: Annotated[
        str, StringConstraints(min_length=1, strip_whitespace=True)
    ] = Field(description="Name of the test")
    sutCode: Annotated[
        str, StringConstraints(min_length=1, strip_whitespace=True)
    ] = Field(description="SUT Code of the test")
    name: Annotated[
        str, StringConstraints(min_length=1, strip_whitespace=True)
    ] = Field(description="Full name of the test")
    date: datetime = Field(
        default_factory=partial(datetime.now, UTC),
        description="Date when the test was conducted"
    )
    testDescription: Optional[str] = Field(
        default=None, description="Description of the test"
    )

    # Embedded subtests
    subtests: List[SubTest] = Field(
        default_factory=list, description="List of embedded subtests"
    )

    # References
    patientId: PyObjectId = Field(description="ID of the patient who took the test")
    practitioner: Optional[
        Annotated[str, StringConstraints(min_length=1, strip_whitespace=True)]
    ] = Field(default=None, description="The practitioner who ordered the test")
    hospitalVisitId: Optional[PyObjectId] = Field(
        default=None, description="ID of the hospital visit during which this test was ordered"
    )


