"""Home Assistant source schemas (CRUD + test + entities)."""

from datetime import datetime
from typing import List

from pydantic import BaseModel, Field


class HomeAssistantSourceCreate(BaseModel):
    """Request to create a Home Assistant source."""

    name: str = Field(description="Source name", min_length=1, max_length=100)
    host: str = Field(description="HA host:port (e.g. '192.168.1.100:8123')", min_length=1)
    token: str = Field(description="Long-Lived Access Token", min_length=1)
    use_ssl: bool = Field(default=False, description="Use wss:// instead of ws://")
    entity_filters: List[str] = Field(
        default_factory=list, description="Entity ID filter patterns (e.g. ['sensor.*'])"
    )
    description: str | None = Field(None, description="Optional description", max_length=500)
    tags: List[str] = Field(default_factory=list, description="User-defined tags")
    icon: str | None = Field(
        None,
        max_length=64,
        description="Icon id from the curated icon library. Pass empty string to clear.",
    )
    icon_color: str | None = Field(
        None,
        max_length=32,
        description="Optional CSS color override for the icon (e.g. '#4CAF50'). Empty/null inherits the channel accent.",
    )


class HomeAssistantSourceUpdate(BaseModel):
    """Request to update a Home Assistant source."""

    name: str | None = Field(None, description="Source name", min_length=1, max_length=100)
    host: str | None = Field(None, description="HA host:port", min_length=1)
    token: str | None = Field(None, description="Long-Lived Access Token", min_length=1)
    use_ssl: bool | None = Field(None, description="Use wss://")
    entity_filters: List[str] | None = Field(None, description="Entity ID filter patterns")
    description: str | None = Field(None, description="Optional description", max_length=500)
    tags: List[str] | None = None
    icon: str | None = Field(
        None,
        max_length=64,
        description="Icon id from the curated icon library. Pass empty string to clear.",
    )
    icon_color: str | None = Field(
        None,
        max_length=32,
        description="Optional CSS color override for the icon. Pass empty string to inherit the channel accent.",
    )


class HomeAssistantSourceResponse(BaseModel):
    """Home Assistant source response."""

    id: str = Field(description="Source ID")
    name: str = Field(description="Source name")
    host: str = Field(description="HA host:port")
    use_ssl: bool = Field(description="Whether SSL is enabled")
    entity_filters: List[str] = Field(default_factory=list, description="Entity filter patterns")
    connected: bool = Field(default=False, description="Whether the WebSocket connection is active")
    entity_count: int = Field(default=0, description="Number of cached entities")
    description: str | None = Field(None, description="Description")
    tags: List[str] = Field(default_factory=list, description="User-defined tags")
    icon: str | None = Field(
        None,
        max_length=64,
        description="Icon id from the curated icon library.",
    )
    icon_color: str | None = Field(
        None,
        max_length=32,
        description="Optional CSS color override for the icon.",
    )
    created_at: datetime = Field(description="Creation timestamp")
    updated_at: datetime = Field(description="Last update timestamp")
    token: str | None = Field(
        None,
        description=(
            "Long-Lived Access Token. Redacted as '***' unless the request "
            "passes ?include_secrets=true with a non-anonymous API key."
        ),
    )


class HomeAssistantSourceListResponse(BaseModel):
    """List of Home Assistant sources."""

    sources: List[HomeAssistantSourceResponse] = Field(description="List of HA sources")
    count: int = Field(description="Number of sources")


class HomeAssistantEntityResponse(BaseModel):
    """A single HA entity."""

    entity_id: str = Field(description="Entity ID (e.g. 'sensor.temperature')")
    state: str = Field(description="Current state value")
    friendly_name: str = Field(description="Human-readable name")
    domain: str = Field(description="Entity domain (e.g. 'sensor', 'binary_sensor')")


class HomeAssistantEntityListResponse(BaseModel):
    """List of entities from a HA instance."""

    entities: List[HomeAssistantEntityResponse] = Field(description="List of entities")
    count: int = Field(description="Number of entities")


class HomeAssistantTestResponse(BaseModel):
    """Connection test result."""

    success: bool = Field(description="Whether connection and auth succeeded")
    ha_version: str | None = Field(None, description="Home Assistant version")
    entity_count: int = Field(default=0, description="Number of entities found")
    error: str | None = Field(None, description="Error message if connection failed")


class HomeAssistantConnectionStatus(BaseModel):
    """Connection status for dashboard indicators."""

    source_id: str
    name: str
    connected: bool
    entity_count: int
    host: str = ""


class HomeAssistantStatusResponse(BaseModel):
    """Overall HA integration status for dashboard."""

    connections: List[HomeAssistantConnectionStatus]
    total_sources: int
    connected_count: int
