"""Pydantic schemas for API validation and serialization."""

from datetime import datetime
from typing import Optional

from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field


class HashtagStreamBase(BaseModel):
    """Base schema for hashtag streams."""

    hashtag: str = Field(..., min_length=1, max_length=100, description="Hashtag to monitor (without #)")
    instance: str = Field(default="mastodon.social", max_length=200, description="Fediverse instance")
    active: bool = Field(default=True, description="Whether the stream is active")


class HashtagStreamCreate(HashtagStreamBase):
    """Schema for creating a new hashtag stream."""

    pass


class HashtagStreamUpdate(BaseModel):
    """Schema for updating a hashtag stream."""

    active: Optional[bool] = None
    instance: Optional[str] = Field(None, max_length=200)


class HashtagStreamResponse(HashtagStreamBase):
    """Schema for hashtag stream response."""

    id: int
    last_check: Optional[datetime] = None
    created_at: datetime
    updated_at: Optional[datetime] = None

    model_config = ConfigDict(from_attributes=True)


class PostBase(BaseModel):
    """Base schema for posts."""

    post_id: str = Field(..., max_length=100, description="Unique post identifier")
    content: str = Field(..., description="Post content")
    author_username: Optional[str] = Field(None, max_length=100)
    author_display_name: Optional[str] = Field(None, max_length=200)
    author_url: Optional[str] = Field(None, max_length=500)
    instance: str = Field(..., max_length=200, description="Source instance")
    hashtags: Optional[list[str]] = None
    boosts: int = Field(default=0, ge=0)
    likes: int = Field(default=0, ge=0)
    replies: int = Field(default=0, ge=0)
    url: Optional[str] = Field(None, max_length=500)
    created_at: Optional[datetime] = None
    spam_score: int = Field(default=0, ge=0, le=100, description="Spam score (0-100)")


class PostCreate(PostBase):
    """Schema for creating a new post."""

    stream_id: int = Field(..., description="Associated hashtag stream ID")


class PostUpdate(BaseModel):
    """Schema for updating a post."""

    processed: Optional[bool] = None
    spam_score: Optional[int] = Field(None, ge=0, le=100)


class PostResponse(PostBase):
    """Schema for post response."""

    id: int
    stream_id: int
    fetched_at: datetime
    processed: bool

    model_config = ConfigDict(from_attributes=True)


class StatsResponse(BaseModel):
    """Schema for application statistics."""

    total_streams: int
    active_streams: int
    total_posts: int
    processed_posts: int
    average_spam_score: Optional[float] = None


class FetchResponse(BaseModel):
    """Schema for fetch operation response."""

    stream_id: int
    hashtag: str
    posts_fetched: int
    posts_saved: int
    success: bool
    error_message: Optional[str] = None
