"""Output target schemas — discriminated unions per target type."""

from datetime import datetime
from typing import Annotated, Any, Dict, List, Literal, Optional, Union

from pydantic import BaseModel, Discriminator, Field, Tag

DEFAULT_STATE_CHECK_INTERVAL = 30  # seconds between health checks

# ---------------------------------------------------------------------------
# BindableFloat — accepts plain number OR {value, source_id} dict
# ---------------------------------------------------------------------------

BindableFloatInput = Union[float, int, Dict[str, Any]]
"""API input type: a plain number (static) or {"value": float, "source_id": str}."""


class BindableFloatSchema(BaseModel):
    """Response schema for a bindable scalar property."""

    value: float = Field(description="Static value (used when source_id is empty)")
    source_id: str = Field(default="", description="Value source ID (empty = static)")


class KeyColorRectangleSchema(BaseModel):
    """A named rectangle for key color extraction (relative coords 0.0-1.0)."""

    name: str = Field(description="Rectangle name", min_length=1, max_length=50)
    x: float = Field(default=0.0, description="Left edge (0.0-1.0)", ge=0.0, le=1.0)
    y: float = Field(default=0.0, description="Top edge (0.0-1.0)", ge=0.0, le=1.0)
    width: float = Field(default=1.0, description="Width (0.0-1.0)", gt=0.0, le=1.0)
    height: float = Field(default=1.0, description="Height (0.0-1.0)", gt=0.0, le=1.0)


class HALightMappingSchema(BaseModel):
    """Maps an LED range to one HA light entity."""

    entity_id: str = Field(description="HA light entity ID (e.g. 'light.living_room')")
    led_start: int = Field(default=0, ge=0, description="Start LED index (0-based)")
    led_end: int = Field(default=-1, description="End LED index (-1 = last)")
    brightness_scale: Optional[BindableFloatInput] = Field(
        default=1.0, description="Brightness multiplier (bindable)"
    )


# =====================================================================
# Response schemas (per-type, discriminated union)
# =====================================================================


class _OutputTargetResponseBase(BaseModel):
    """Shared fields for all output target responses."""

    id: str = Field(description="Target ID")
    name: str = Field(description="Target name")
    description: Optional[str] = Field(None, description="Description")
    tags: List[str] = Field(default_factory=list, description="User-defined tags")
    created_at: datetime = Field(description="Creation timestamp")
    updated_at: datetime = Field(description="Last update timestamp")


class LedOutputTargetResponse(_OutputTargetResponseBase):
    target_type: Literal["led"] = "led"
    device_id: str = Field(default="", description="LED device ID")
    color_strip_source_id: str = Field(default="", description="Color strip source ID")
    brightness: Optional[BindableFloatInput] = Field(None, description="Brightness (bindable)")
    fps: Optional[BindableFloatInput] = Field(None, description="Target send FPS (bindable)")
    keepalive_interval: float = Field(default=1.0, description="Keepalive interval (s)")
    state_check_interval: int = Field(
        default=DEFAULT_STATE_CHECK_INTERVAL, description="Health check interval (s)"
    )
    min_brightness_threshold: Optional[BindableFloatInput] = Field(
        default=0, description="Min brightness threshold (bindable, 0=disabled)"
    )
    adaptive_fps: bool = Field(
        default=False, description="Auto-reduce FPS when device is unresponsive"
    )
    protocol: str = Field(default="ddp", description="Send protocol (ddp or http)")


class HALightOutputTargetResponse(_OutputTargetResponseBase):
    target_type: Literal["ha_light"] = "ha_light"
    ha_source_id: str = Field(default="", description="Home Assistant source ID")
    color_strip_source_id: str = Field(default="", description="Color strip source ID")
    brightness: Optional[BindableFloatInput] = Field(None, description="Brightness (bindable)")
    ha_light_mappings: Optional[List[HALightMappingSchema]] = Field(
        None, description="LED-to-light mappings"
    )
    update_rate: Optional[BindableFloatInput] = Field(
        None, description="Service call rate Hz (bindable)"
    )
    transition: Optional[BindableFloatInput] = Field(
        None, description="HA transition seconds (bindable)"
    )
    color_tolerance: Optional[BindableFloatInput] = Field(
        None, description="RGB delta tolerance (bindable)"
    )
    min_brightness_threshold: Optional[BindableFloatInput] = Field(
        default=0, description="Min brightness threshold (bindable, 0=disabled)"
    )


OutputTargetResponse = Annotated[
    Union[
        Annotated[LedOutputTargetResponse, Tag("led")],
        Annotated[HALightOutputTargetResponse, Tag("ha_light")],
    ],
    Discriminator("target_type"),
]

# =====================================================================
# Create schemas (per-type, discriminated union)
# =====================================================================


class _OutputTargetCreateBase(BaseModel):
    """Shared fields for all output target create requests."""

    name: str = Field(description="Target name", min_length=1, max_length=100)
    description: Optional[str] = Field(None, description="Optional description", max_length=500)
    tags: List[str] = Field(default_factory=list, description="User-defined tags")


class LedOutputTargetCreate(_OutputTargetCreateBase):
    target_type: Literal["led"] = "led"
    device_id: str = Field(default="", description="LED device ID")
    color_strip_source_id: str = Field(default="", description="Color strip source ID")
    brightness: Optional[BindableFloatInput] = Field(
        default=1.0, description="Brightness (bindable)"
    )
    fps: Optional[BindableFloatInput] = Field(
        default=30, description="Target send FPS (bindable, 1-90)"
    )
    keepalive_interval: float = Field(
        default=1.0,
        description="Keepalive send interval when screen is static (0.5-5.0s)",
        ge=0.5,
        le=5.0,
    )
    state_check_interval: int = Field(
        default=DEFAULT_STATE_CHECK_INTERVAL,
        description="Device health check interval (5-600s)",
        ge=5,
        le=600,
    )
    min_brightness_threshold: Optional[BindableFloatInput] = Field(
        default=0,
        description="Min brightness threshold (bindable, 0=disabled); below this -> off",
    )
    adaptive_fps: bool = Field(
        default=False, description="Auto-reduce FPS when device is unresponsive"
    )
    protocol: str = Field(
        default="ddp",
        pattern="^(ddp|http)$",
        description="Send protocol: ddp (UDP) or http (JSON API)",
    )


class HALightOutputTargetCreate(_OutputTargetCreateBase):
    target_type: Literal["ha_light"] = "ha_light"
    ha_source_id: str = Field(default="", description="Home Assistant source ID")
    color_strip_source_id: str = Field(default="", description="Color strip source ID")
    brightness: Optional[BindableFloatInput] = Field(
        default=1.0, description="Brightness (bindable)"
    )
    ha_light_mappings: Optional[List[HALightMappingSchema]] = Field(
        None, description="LED-to-light mappings"
    )
    update_rate: Optional[BindableFloatInput] = Field(
        default=2.0, description="Service call rate in Hz (bindable)"
    )
    transition: Optional[BindableFloatInput] = Field(
        default=0.5, description="HA transition seconds (bindable)"
    )
    color_tolerance: Optional[BindableFloatInput] = Field(
        default=5, description="RGB delta tolerance (bindable)"
    )
    min_brightness_threshold: Optional[BindableFloatInput] = Field(
        default=0,
        description="Min brightness threshold (bindable, 0=disabled); below this -> off",
    )


OutputTargetCreate = Annotated[
    Union[
        Annotated[LedOutputTargetCreate, Tag("led")],
        Annotated[HALightOutputTargetCreate, Tag("ha_light")],
    ],
    Discriminator("target_type"),
]

# =====================================================================
# Update schemas (per-type, discriminated union)
# =====================================================================


class _OutputTargetUpdateBase(BaseModel):
    """Shared fields for all output target update requests."""

    name: Optional[str] = Field(None, description="Target name", min_length=1, max_length=100)
    description: Optional[str] = Field(None, description="Optional description", max_length=500)
    tags: Optional[List[str]] = None


class LedOutputTargetUpdate(_OutputTargetUpdateBase):
    target_type: Literal["led"] = "led"
    device_id: Optional[str] = Field(None, description="LED device ID")
    color_strip_source_id: Optional[str] = Field(None, description="Color strip source ID")
    brightness: Optional[BindableFloatInput] = Field(None, description="Brightness (bindable)")
    fps: Optional[BindableFloatInput] = Field(None, description="Target send FPS (bindable, 1-90)")
    keepalive_interval: Optional[float] = Field(
        None, description="Keepalive interval (0.5-5.0s)", ge=0.5, le=5.0
    )
    state_check_interval: Optional[int] = Field(
        None, description="Health check interval (5-600s)", ge=5, le=600
    )
    min_brightness_threshold: Optional[BindableFloatInput] = Field(
        None, description="Min brightness threshold (bindable, 0=disabled)"
    )
    adaptive_fps: Optional[bool] = Field(
        None, description="Auto-reduce FPS when device is unresponsive"
    )
    protocol: Optional[str] = Field(
        None, pattern="^(ddp|http)$", description="Send protocol: ddp (UDP) or http (JSON API)"
    )


class HALightOutputTargetUpdate(_OutputTargetUpdateBase):
    target_type: Literal["ha_light"] = "ha_light"
    ha_source_id: Optional[str] = Field(None, description="Home Assistant source ID")
    color_strip_source_id: Optional[str] = Field(None, description="Color strip source ID")
    brightness: Optional[BindableFloatInput] = Field(None, description="Brightness (bindable)")
    ha_light_mappings: Optional[List[HALightMappingSchema]] = Field(
        None, description="LED-to-light mappings"
    )
    update_rate: Optional[BindableFloatInput] = Field(
        None, description="Service call rate Hz (bindable)"
    )
    transition: Optional[BindableFloatInput] = Field(
        None, description="HA transition seconds (bindable)"
    )
    color_tolerance: Optional[BindableFloatInput] = Field(
        None, description="RGB delta tolerance (bindable)"
    )
    min_brightness_threshold: Optional[BindableFloatInput] = Field(
        None, description="Min brightness threshold (bindable, 0=disabled)"
    )


OutputTargetUpdate = Annotated[
    Union[
        Annotated[LedOutputTargetUpdate, Tag("led")],
        Annotated[HALightOutputTargetUpdate, Tag("ha_light")],
    ],
    Discriminator("target_type"),
]

# =====================================================================
# List response & utility schemas
# =====================================================================


class OutputTargetListResponse(BaseModel):
    """List of output targets response."""

    targets: List[OutputTargetResponse] = Field(description="List of output targets")
    count: int = Field(description="Number of targets")


class TargetProcessingState(BaseModel):
    """Processing state for an output target."""

    target_id: str = Field(description="Target ID")
    device_id: Optional[str] = Field(None, description="Device ID")
    color_strip_source_id: str = Field(default="", description="Color strip source ID")
    processing: bool = Field(description="Whether processing is active")
    fps_actual: Optional[float] = Field(None, description="Actual FPS achieved")
    fps_potential: Optional[float] = Field(
        None, description="Potential FPS (processing speed without throttle)"
    )
    fps_target: Optional[int] = Field(None, description="Target FPS")
    frames_skipped: Optional[int] = Field(None, description="Frames skipped (no screen change)")
    frames_keepalive: Optional[int] = Field(
        None, description="Keepalive frames sent during standby"
    )
    fps_current: Optional[int] = Field(None, description="Frames sent in the last second")
    timing_send_ms: Optional[float] = Field(None, description="DDP send time (ms)")
    timing_extract_ms: Optional[float] = Field(
        None, description="Border pixel extraction time (ms)"
    )
    timing_map_leds_ms: Optional[float] = Field(None, description="LED color mapping time (ms)")
    timing_smooth_ms: Optional[float] = Field(None, description="Temporal smoothing time (ms)")
    timing_total_ms: Optional[float] = Field(
        None, description="Total processing time per frame (ms)"
    )
    timing_audio_read_ms: Optional[float] = Field(None, description="Audio device read time (ms)")
    timing_audio_fft_ms: Optional[float] = Field(None, description="Audio FFT analysis time (ms)")
    timing_audio_render_ms: Optional[float] = Field(
        None, description="Audio visualization render time (ms)"
    )
    display_index: Optional[int] = Field(None, description="Current display index")
    overlay_active: bool = Field(
        default=False, description="Whether visualization overlay is active"
    )
    last_update: Optional[datetime] = Field(None, description="Last successful update")
    errors: List[str] = Field(default_factory=list, description="Recent errors")
    device_online: bool = Field(default=False, description="Whether device is reachable")
    device_latency_ms: Optional[float] = Field(None, description="Health check latency in ms")
    device_name: Optional[str] = Field(None, description="Device name reported by firmware")
    device_version: Optional[str] = Field(None, description="Firmware version")
    device_led_count: Optional[int] = Field(None, description="LED count reported by device")
    device_rgbw: Optional[bool] = Field(None, description="Whether device uses RGBW LEDs")
    device_led_type: Optional[str] = Field(
        None, description="LED chip type (e.g. WS2812B, SK6812 RGBW)"
    )
    device_fps: Optional[int] = Field(
        None, description="Device-reported FPS (WLED internal refresh rate)"
    )
    device_last_checked: Optional[datetime] = Field(None, description="Last health check time")
    device_error: Optional[str] = Field(None, description="Last health check error")
    device_streaming_reachable: Optional[bool] = Field(
        None, description="Device reachable during streaming (HTTP probe)"
    )
    fps_effective: Optional[int] = Field(None, description="Effective FPS after adaptive reduction")


class TargetMetricsResponse(BaseModel):
    """Target metrics response."""

    target_id: str = Field(description="Target ID")
    device_id: Optional[str] = Field(None, description="Device ID")
    processing: bool = Field(description="Whether processing is active")
    fps_actual: Optional[float] = Field(None, description="Actual FPS")
    fps_target: Optional[int] = Field(None, description="Target FPS")
    uptime_seconds: float = Field(description="Processing uptime in seconds")
    frames_processed: int = Field(description="Total frames processed")
    errors_count: int = Field(description="Total error count")
    last_error: Optional[str] = Field(None, description="Last error message")
    last_update: Optional[datetime] = Field(None, description="Last update timestamp")


class BulkTargetRequest(BaseModel):
    """Request body for bulk start/stop operations."""

    ids: List[str] = Field(description="List of target IDs to operate on")


class BulkTargetResponse(BaseModel):
    """Response for bulk start/stop operations."""

    started: List[str] = Field(
        default_factory=list, description="IDs that were successfully started"
    )
    stopped: List[str] = Field(
        default_factory=list, description="IDs that were successfully stopped"
    )
    errors: Dict[str, str] = Field(
        default_factory=dict, description="Map of target ID to error message for failures"
    )
