"""Request models for API endpoints."""

from typing import Optional, List

from pydantic import BaseModel, Field, validator


class TracklistEntry(BaseModel):
    """A single track entry from the tracklist."""

    ts: str = Field(..., description="Timestamp (e.g., '00:00' or '00:00-01:30')")
    tn: Optional[str] = Field("", description="Track name")
    an: Optional[str] = Field("", description="Author/artist")
    al: Optional[str] = Field("", description="Album")
    date: Optional[str] = Field("", description="Date/year")
    ext: Optional[str] = Field("", description="File extension")

    @validator("ts")
    def validate_timestamp(cls, v: str) -> str:
        """Basic timestamp validation (format and range)."""
        v = v.strip()
        if not v:
            raise ValueError("Timestamp cannot be empty")

        # Check for range format (start-end)
        if "-" in v:
            parts = v.split("-", 1)
            start = parts[0].strip()
            end = parts[1].strip()
            if not start or not end:
                raise ValueError("Invalid range format. Expected 'start-end'")
            # Validate each part with the same logic
            for ts in [start, end]:
                cls._validate_single_timestamp(ts)
        else:
            cls._validate_single_timestamp(v)

        return v

    @staticmethod
    def _validate_single_timestamp(ts: str) -> None:
        """Validate a single timestamp (mm:ss or HH:MM:SS)."""
        parts = ts.split(":")
        if len(parts) not in (2, 3):
            raise ValueError(f"Invalid timestamp format: {ts}. Expected mm:ss or HH:MM:SS")
        try:
            for p in parts:
                int(p)
        except ValueError:
            raise ValueError(f"Invalid timestamp: {ts}. Must contain only numbers.")


class SplitRequest(BaseModel):
    """Request model for the split endpoint."""

    task_id: str = Field(..., description="Task ID from upload")
    tracklist: List[TracklistEntry] = Field(..., description="List of tracks")
    options: dict = Field(default_factory=dict, description="All CLI options")