"""Pydantic v2 schemas for the AI Proactive plugin API."""

from __future__ import annotations

from datetime import datetime
from typing import Any

from pydantic import BaseModel, Field


class ContextReport(BaseModel):
    """Frontend reports the current page/entity context."""

    page: str = Field(..., description="Current page path")
    entity_type: str | None = Field(None, description="Entity type being viewed")
    entity_id: str | None = Field(None, description="Entity ID being viewed")
    entity_data: dict[str, Any] | None = Field(
        None, description="Additional entity metadata"
    )


class SuggestionAction(BaseModel):
    """A suggested CRM action."""

    method: str = Field(..., description="HTTP method")
    path: str = Field(..., description="API path")
    body: dict[str, Any] | None = Field(None, description="Request body")
    description: str = Field(..., description="Human-readable description")


class SuggestionResponse(BaseModel):
    """API response for a single suggestion."""

    id: str
    entity_type: str
    entity_id: str | None
    suggestion_type: str
    title: str
    content: str
    confidence: float
    actions: list[dict[str, Any]]
    created_at: datetime
    is_dismissed: bool
    is_acted_upon: bool = False


class SuggestionListResponse(BaseModel):
    """Paginated list of suggestions."""

    items: list[SuggestionResponse]
    total: int


class ActRequest(BaseModel):
    """Execute a suggested action by index."""

    action_index: int = Field(..., ge=0, description="Index into actions array")


class ActResponse(BaseModel):
    """Result of executing a suggested action."""

    success: bool
    data: dict[str, Any] | None = None
    error: str | None = None


class SettingsResponse(BaseModel):
    """Proactive AI settings for the current user."""

    enabled: bool
    suggestion_categories: list[str]
    confidence_threshold: float
    rate_limit_seconds: int
    model: str
    heartbeat_enabled: bool = True
    heartbeat_interval_seconds: int = 300
    heartbeat_target_room: str = "Live KI"
    available_models: list[str] = Field(default_factory=lambda: [
        'ollama/deepseek-v4-flash',
        'ollama/deepseek-v4-pro',
        'ollama/llama3.2',
        'ollama/gpt-4o-mini',
        'gpt-4o-mini',
    ])


class SettingsUpdate(BaseModel):
    """Partial update for proactive AI settings."""

    enabled: bool | None = None
    suggestion_categories: list[str] | None = None
    confidence_threshold: float | None = None
    rate_limit_seconds: int | None = None
    model: str | None = None
    heartbeat_enabled: bool | None = None
    heartbeat_interval_seconds: int | None = None
    heartbeat_target_room: str | None = None


class StatsResponse(BaseModel):
    """Proactive AI usage statistics."""

    total_suggestions: int = 0
    dismissed: int = 0
    acted_upon: int = 0
    active: int = 0
    dismiss_rate: float = 0.0
    act_rate: float = 0.0
