"""Pydantic schemas for notification system."""
from datetime import datetime
from uuid import UUID

from pydantic import BaseModel, Field, field_validator


VALID_EVENTS = {
    "session.escalated",
    "session.high_priority",
    "proposal.pending",
    "proposal.approved",
    "knowledge_gap.detected",
}


class NotificationConfigCreate(BaseModel):
    channel: str = Field(..., pattern="^(email|slack_webhook|teams_webhook)$")
    webhook_url: str | None = None
    email_addresses: list[str] | None = None
    events_enabled: dict[str, bool] = Field(
        default_factory=lambda: {e: True for e in VALID_EVENTS}
    )

    @field_validator("events_enabled")
    @classmethod
    def validate_event_keys(cls, v: dict[str, bool]) -> dict[str, bool]:
        invalid = set(v) - VALID_EVENTS
        if invalid:
            raise ValueError(f"Unknown event keys: {invalid}")
        return v


class NotificationConfigUpdate(BaseModel):
    webhook_url: str | None = None
    email_addresses: list[str] | None = None
    is_active: bool | None = None
    events_enabled: dict[str, bool] | None = None

    @field_validator("events_enabled")
    @classmethod
    def validate_event_keys(cls, v: dict[str, bool] | None) -> dict[str, bool] | None:
        if v is not None:
            invalid = set(v) - VALID_EVENTS
            if invalid:
                raise ValueError(f"Unknown event keys: {invalid}")
        return v


class NotificationConfigResponse(BaseModel):
    id: UUID
    channel: str
    webhook_url: str | None
    email_addresses: list[str] | None
    is_active: bool
    events_enabled: dict[str, bool]
    created_at: datetime
    updated_at: datetime

    model_config = {"from_attributes": True}


class NotificationResponse(BaseModel):
    id: UUID
    event: str
    title: str
    body: str | None
    link: str | None
    is_read: bool
    created_at: datetime

    model_config = {"from_attributes": True}


class UnreadCountResponse(BaseModel):
    count: int


class NotificationTestRequest(BaseModel):
    config_id: UUID


class NotificationTestResponse(BaseModel):
    success: bool
    message: str
