"""Models for application settings with SQLModel support"""
import uuid
import json
from pydantic import BaseModel, Field as PydanticField
from typing import Optional, List, Dict
from datetime import datetime
from sqlmodel import SQLModel, Field, Column, String


class AppSettingsBase(SQLModel):
    """Base schema for application settings"""
    default_lang: str = Field(default="vostfr")
    theme: str = Field(default="dark")
    
    # Store list of disabled providers as a JSON string
    disabled_providers_json: str = Field(default="[]", sa_column=Column(String))

    # #9: Filter for recommendations section ("all", "anime", "series")
    recommendations_filter: str = Field(default="all", sa_column=Column(String))

    # #10: Filter for latest releases section ("all", "anime", "series")
    releases_filter: str = Field(default="all", sa_column=Column(String))

    # #11: Enable/disable categories
    anime_enabled: bool = Field(default=True)
    series_enabled: bool = Field(default=True)

    # #12: Custom download directory
    download_dir: str = Field(default="downloads")
    
    @property
    def disabled_providers(self) -> List[str]:
        try:
            return json.loads(self.disabled_providers_json or "[]")
        except:
            return []
    
    @disabled_providers.setter
    def disabled_providers(self, value: List[str]):
        self.disabled_providers_json = json.dumps(value or [])


class AppSettingsTable(AppSettingsBase, table=True):
    """Database table for application settings"""
    __tablename__ = "app_settings"
    
    id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        primary_key=True,
        index=True,
        nullable=False
    )
    user_id: str = Field(foreign_key="users.id", index=True, unique=True)
    updated_at: datetime = Field(default_factory=datetime.now)


class AppSettings(BaseModel):
    """Application settings (API Response)"""
    default_lang: str = "vostfr"
    theme: str = "dark"
    disabled_providers: List[str] = []
    recommendations_filter: str = "all"
    releases_filter: str = "all"
    anime_enabled: bool = True
    series_enabled: bool = True
    download_dir: str = "downloads"
    
    class Config:
        from_attributes = True


class AppSettingsUpdate(BaseModel):
    """Model for updating application settings"""
    default_lang: Optional[str] = None
    theme: Optional[str] = None
    disabled_providers: Optional[List[str]] = None
    recommendations_filter: Optional[str] = None
    releases_filter: Optional[str] = None
    anime_enabled: Optional[bool] = None
    series_enabled: Optional[bool] = None
    download_dir: Optional[str] = None
