import uuid
from datetime import datetime

from pydantic import BaseModel, Field, field_validator

VALID_PLATFORMS = {"wenxin", "kimi", "tongyi", "baidu_ai", "yuanbao", "qingyan", "doubao", "tiangong", "xinghuo"}
VALID_FREQUENCIES = {"daily", "weekly"}
VALID_STATUSES = {"active", "paused", "disabled"}


class QueryCreate(BaseModel):
    keyword: str = Field(min_length=1, max_length=200)
    target_brand: str = Field(min_length=1, max_length=100)
    brand_aliases: list[str] | None = None
    platforms: list[str]
    frequency: str = "weekly"

    @field_validator("platforms")
    @classmethod
    def validate_platforms(cls, v: list[str]) -> list[str]:
        if not v:
            raise ValueError("platforms cannot be empty")
        invalid = set(v) - VALID_PLATFORMS
        if invalid:
            raise ValueError(f"invalid platforms: {', '.join(invalid)}")
        return v

    @field_validator("frequency")
    @classmethod
    def validate_frequency(cls, v: str) -> str:
        if v not in VALID_FREQUENCIES:
            raise ValueError(f"frequency must be one of {VALID_FREQUENCIES}")
        return v


class QueryUpdate(BaseModel):
    keyword: str | None = Field(default=None, min_length=1, max_length=200)
    target_brand: str | None = Field(default=None, min_length=1, max_length=100)
    brand_aliases: list[str] | None = None
    platforms: list[str] | None = None
    frequency: str | None = None
    status: str | None = None

    @field_validator("platforms")
    @classmethod
    def validate_platforms(cls, v: list[str] | None) -> list[str] | None:
        if v is None:
            return v
        if not v:
            raise ValueError("platforms cannot be empty")
        invalid = set(v) - VALID_PLATFORMS
        if invalid:
            raise ValueError(f"invalid platforms: {', '.join(invalid)}")
        return v

    @field_validator("frequency")
    @classmethod
    def validate_frequency(cls, v: str | None) -> str | None:
        if v is None:
            return v
        if v not in VALID_FREQUENCIES:
            raise ValueError(f"frequency must be one of {VALID_FREQUENCIES}")
        return v

    @field_validator("status")
    @classmethod
    def validate_status(cls, v: str | None) -> str | None:
        if v is None:
            return v
        if v not in VALID_STATUSES:
            raise ValueError(f"status must be one of {VALID_STATUSES}")
        return v


class QueryResponse(BaseModel):
    id: uuid.UUID
    keyword: str
    target_brand: str
    brand_aliases: list
    platforms: list
    frequency: str
    status: str
    last_queried_at: datetime | None
    next_query_at: datetime | None
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class QueryListResponse(BaseModel):
    items: list[QueryResponse]
    total: int
