"""Pydantic schemas for game integration API endpoints."""

from datetime import datetime
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field


# ── Event Mapping ──────────────────────────────────────────────────────────


class EventMappingSchema(BaseModel):
    """Maps a standard game event type to a visual effect."""

    event_type: str = Field(description="Standard event type (e.g. 'health', 'kill')")
    effect: str = Field(default="flash", description="Effect name (flash, pulse, gradient)")
    color: List[int] = Field(
        default=[255, 0, 0],
        description="RGB color [R, G, B] (0-255 each)",
        min_length=3,
        max_length=3,
    )
    duration_ms: int = Field(default=500, ge=0, le=60000, description="Effect duration in ms")
    intensity: float = Field(default=1.0, ge=0.0, le=1.0, description="Effect intensity 0.0-1.0")
    priority: int = Field(default=0, ge=0, le=100, description="Priority for effect stacking")


# ── CRUD Schemas ───────────────────────────────────────────────────────────


class GameIntegrationCreate(BaseModel):
    """Request to create a game integration config."""

    name: str = Field(description="Integration name", min_length=1, max_length=100)
    adapter_type: str = Field(description="Adapter type identifier", min_length=1)
    enabled: bool = Field(default=True, description="Whether integration is active")
    adapter_config: Dict[str, Any] = Field(
        default_factory=dict, description="Adapter-specific settings"
    )
    event_mappings: List[EventMappingSchema] = Field(
        default_factory=list, description="Event-to-effect mappings"
    )
    description: Optional[str] = Field(None, description="Integration description", max_length=500)
    tags: List[str] = Field(default_factory=list, description="User-defined tags")


class GameIntegrationUpdate(BaseModel):
    """Request to update a game integration config."""

    name: Optional[str] = Field(None, description="Integration name", min_length=1, max_length=100)
    adapter_type: Optional[str] = Field(None, description="Adapter type identifier", min_length=1)
    enabled: Optional[bool] = Field(None, description="Whether integration is active")
    adapter_config: Optional[Dict[str, Any]] = Field(None, description="Adapter-specific settings")
    event_mappings: Optional[List[EventMappingSchema]] = Field(
        None, description="Event-to-effect mappings"
    )
    description: Optional[str] = Field(None, description="Integration description", max_length=500)
    tags: Optional[List[str]] = Field(None, description="User-defined tags")


class GameIntegrationResponse(BaseModel):
    """Game integration config response."""

    id: str = Field(description="Integration ID")
    name: str = Field(description="Integration name")
    adapter_type: str = Field(description="Adapter type identifier")
    enabled: bool = Field(description="Whether integration is active")
    adapter_config: Dict[str, Any] = Field(description="Adapter-specific settings")
    event_mappings: List[EventMappingSchema] = Field(description="Event-to-effect mappings")
    created_at: datetime = Field(description="Creation timestamp")
    updated_at: datetime = Field(description="Last update timestamp")
    description: Optional[str] = Field(None, description="Integration description")
    tags: List[str] = Field(default_factory=list, description="User-defined tags")


class GameIntegrationListResponse(BaseModel):
    """List of game integration configs."""

    integrations: List[GameIntegrationResponse] = Field(
        description="List of game integration configs"
    )
    count: int = Field(description="Number of integrations")


# ── Event Ingestion ────────────────────────────────────────────────────────


class GameEventPayload(BaseModel):
    """Incoming game event payload from a game client.

    The shape depends on the adapter — this is a generic envelope.
    The adapter's parse_payload() extracts standardized events.
    """

    data: Dict[str, Any] = Field(description="Raw game event data")


# ── Adapter Metadata ───────────────────────────────────────────────────────


class AdapterInfoResponse(BaseModel):
    """Metadata for a registered game adapter."""

    adapter_type: str = Field(description="Adapter type identifier")
    display_name: str = Field(description="Human-readable adapter name")
    game_name: str = Field(description="Game this adapter supports")
    supported_events: List[str] = Field(description="Standard event types supported")
    config_schema: List[Dict[str, Any]] = Field(description="Flat list of config fields")
    setup_instructions: str = Field(description="Markdown setup guide")
    supports_auto_setup: bool = Field(
        default=False, description="Whether this adapter supports automatic config setup"
    )


class AdapterListResponse(BaseModel):
    """List of available game adapters."""

    adapters: List[AdapterInfoResponse] = Field(description="Available adapters")
    count: int = Field(description="Number of adapters")


# ── Status / Diagnostics ──────────────────────────────────────────────────


class GameIntegrationStatusResponse(BaseModel):
    """Runtime status for a game integration."""

    integration_id: str = Field(description="Integration ID")
    enabled: bool = Field(description="Whether integration is active")
    connected: bool = Field(description="Whether adapter is currently receiving data")
    last_event_time: Optional[float] = Field(None, description="Monotonic timestamp of last event")
    event_count: int = Field(default=0, description="Total events received")
    event_counts_by_type: Dict[str, int] = Field(
        default_factory=dict, description="Event counts per event type"
    )


class GameEventResponse(BaseModel):
    """A single game event for diagnostics."""

    adapter_id: str = Field(description="Adapter that produced this event")
    event_type: str = Field(description="Standard event type")
    value: float = Field(description="Normalized value 0.0-1.0")
    timestamp: float = Field(description="Monotonic timestamp")
    raw_data: Dict[str, Any] = Field(default_factory=dict, description="Original game data")


class RecentEventsResponse(BaseModel):
    """Recent events for a game integration."""

    integration_id: str = Field(description="Integration ID")
    events: List[GameEventResponse] = Field(description="Recent events (newest last)")
    count: int = Field(description="Number of events returned")


# ── Presets ──────────────────────────────────────────────────────────────


class EffectPresetResponse(BaseModel):
    """A built-in effect preset."""

    key: str = Field(description="Unique preset key")
    name: str = Field(description="Display name")
    description: str = Field(description="One-line description")
    target_game_types: List[str] = Field(description="Genre tags (fps, moba, racing, any)")
    event_mappings: List[EventMappingSchema] = Field(description="Pre-configured mappings")


class PresetListResponse(BaseModel):
    """List of available effect presets."""

    presets: List[EffectPresetResponse] = Field(description="Available presets")
    count: int = Field(description="Number of presets")


class ApplyPresetRequest(BaseModel):
    """Request to apply a preset to an integration."""

    preset_key: str = Field(description="Key of the preset to apply")
    replace: bool = Field(
        default=False,
        description="If true, replace existing mappings; if false, append",
    )


class AutoSetupResponse(BaseModel):
    """Result of an auto-setup operation."""

    success: bool = Field(description="Whether the setup completed successfully")
    file_path: str = Field(default="", description="Path to the config file written")
    message: str = Field(description="Human-readable result message")
    token_generated: bool = Field(
        default=False, description="Whether a new auth token was auto-generated"
    )
