from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field

from .db_models import Difficulty


# ============== Opening Schemas ==============

class OpeningPosterBase(BaseModel):
    poster_file: str
    is_default: bool = False


class OpeningPosterCreate(OpeningPosterBase):
    pass


class OpeningPosterResponse(OpeningPosterBase):
    id: int
    opening_id: int
    created_at: datetime

    class Config:
        from_attributes = True


class OpeningBase(BaseModel):
    anime_name: str = Field(..., min_length=1, max_length=255)
    op_number: str = Field(..., min_length=1, max_length=20)
    song_name: Optional[str] = Field(None, max_length=255)
    audio_file: str = Field(..., min_length=1)


class OpeningCreate(OpeningBase):
    poster_files: List[str] = Field(default_factory=list)


class OpeningUpdate(BaseModel):
    anime_name: Optional[str] = Field(None, min_length=1, max_length=255)
    op_number: Optional[str] = Field(None, min_length=1, max_length=20)
    song_name: Optional[str] = Field(None, max_length=255)
    audio_file: Optional[str] = None


class OpeningResponse(OpeningBase):
    id: int
    last_usage: Optional[datetime] = None
    created_at: datetime
    updated_at: datetime
    posters: List[OpeningPosterResponse] = []

    class Config:
        from_attributes = True


class OpeningListResponse(BaseModel):
    openings: List[OpeningResponse]
    total: int


# ============== Background Schemas ==============

class BackgroundBase(BaseModel):
    name: str = Field(..., min_length=1, max_length=255)
    video_file: str = Field(..., min_length=1)
    difficulty: Difficulty = Difficulty.MEDIUM


class BackgroundCreate(BackgroundBase):
    pass


class BackgroundUpdate(BaseModel):
    name: Optional[str] = Field(None, min_length=1, max_length=255)
    video_file: Optional[str] = None
    difficulty: Optional[Difficulty] = None


class BackgroundResponse(BackgroundBase):
    id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


class BackgroundListResponse(BaseModel):
    backgrounds: List[BackgroundResponse]
    total: int


# ============== Poster Management ==============

class AddPosterRequest(BaseModel):
    poster_file: str
    is_default: bool = False


class SetDefaultPosterRequest(BaseModel):
    poster_id: int
