"""Test Run Schema"""
from datetime import datetime, timezone
from typing import List, Optional

from pydantic import AnyHttpUrl, BaseModel, ConfigDict, field_validator

from .limits import Limits
from .result import Result


class RunBase(BaseModel):
    """Test Run Base schema."""

    operator_id: Optional[int] = None
    serial_number: Optional[str] = None
    slot_id: Optional[str] = None
    api_url: Optional[AnyHttpUrl] = None
    test_plan_version: Optional[str] = None
    start: Optional[str] = None
    duration: Optional[float] = None
    passed: Optional[bool] = None
    log_file: Optional[str] = None
    num_failed: Optional[int] = None
    num_passed: Optional[int] = None
    num_skipped: Optional[int] = None


class RunCreate(RunBase):
    """Test Run Create schema."""

    operator_id: int
    slot_id: str
    api_url: Optional[AnyHttpUrl]
    start: str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")

    @field_validator("api_url", mode="after")
    @classmethod
    def coerce_url_to_str(cls, v) -> Optional[str]:
        return str(v) if v else None


class RunUpdate(RunBase):
    """Test Run Update schema."""

    pass


class RunInDBBase(RunBase):
    """Test Run Database base schema."""

    id: int
    uuid: str
    plan_id: int
    limits_id: Optional[int] = None
    results_id: Optional[int] = None
    results: Optional[List[Result]] = None
    limits: Optional[Limits] = None

    model_config = ConfigDict(from_attributes=True)


class RunBaseInDBBase(RunBase):
    """Test Run Database base schema."""

    id: int
    uuid: str
    plan_id: int

    model_config = ConfigDict(from_attributes=True)


class Run(RunInDBBase):
    """Test Run schema."""

    pass


class RunInDB(RunInDBBase):
    pass


class ResultWithRun(Result):
    """Test Result Bundled with Run schema."""

    run: RunBaseInDBBase = None
