"""Automation-related schemas."""

from datetime import datetime
from typing import List

from pydantic import BaseModel, Field


class RuleSchema(BaseModel):
    """A single rule within an automation."""

    rule_type: str = Field(description="Rule type discriminator (e.g. 'application')")
    # Application rule fields
    apps: List[str] | None = Field(None, description="Process names (for application rule)")
    match_type: str | None = Field(
        None, description="'running' or 'topmost' (for application rule)"
    )
    # Time-of-day rule fields
    start_time: str | None = Field(None, description="Start time HH:MM (for time_of_day rule)")
    end_time: str | None = Field(None, description="End time HH:MM (for time_of_day rule)")
    # System idle rule fields
    idle_minutes: int | None = Field(
        None, description="Idle timeout in minutes (for system_idle rule)"
    )
    when_idle: bool | None = Field(None, description="True=active when idle (for system_idle rule)")
    # Display state rule fields
    state: str | None = Field(None, description="'on' or 'off' (for display_state rule)")
    # MQTT rule fields
    mqtt_source_id: str | None = Field(None, description="MQTT source ID (for mqtt rule)")
    topic: str | None = Field(None, description="MQTT topic to watch (for mqtt rule)")
    payload: str | None = Field(None, description="Expected payload value (for mqtt rule)")
    match_mode: str | None = Field(
        None, description="'exact', 'contains', or 'regex' (for mqtt rule)"
    )
    # Webhook rule fields
    token: str | None = Field(None, description="Secret token for webhook URL (for webhook rule)")
    # Home Assistant rule fields
    ha_source_id: str | None = Field(
        None, description="Home Assistant source ID (for home_assistant rule)"
    )
    entity_id: str | None = Field(
        None,
        description="HA entity ID, e.g. 'binary_sensor.front_door' (for home_assistant rule)",
    )
    # HTTP poll rule fields
    value_source_id: str | None = Field(
        None,
        description=(
            "Value source ID (for http_poll rule). The referenced "
            "ValueSource must be of source_type='http'."
        ),
    )
    operator: str | None = Field(
        None,
        description=(
            "Comparison operator for http_poll rule: "
            "'equals', 'not_equals', 'contains', 'regex', 'gt', 'lt', 'exists'."
        ),
    )
    value: str | None = Field(
        None, description="Expected value (for http_poll rule; ignored for 'exists')"
    )


# Backward-compatible alias
ConditionSchema = RuleSchema


class AutomationCreate(BaseModel):
    """Request to create an automation."""

    name: str = Field(description="Automation name", min_length=1, max_length=100)
    enabled: bool = Field(default=True, description="Whether the automation is enabled")
    rule_logic: str = Field(default="or", description="How rules combine: 'or' or 'and'")
    rules: List[RuleSchema] = Field(default_factory=list, description="List of rules")
    scene_preset_id: str | None = Field(None, description="Scene preset to activate")
    deactivation_mode: str = Field(
        default="none", description="'none', 'revert', or 'fallback_scene'"
    )
    deactivation_scene_preset_id: str | None = Field(
        None, description="Scene preset for fallback deactivation"
    )
    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. Empty/null inherits the channel accent.",
    )


class AutomationUpdate(BaseModel):
    """Request to update an automation."""

    name: str | None = Field(None, description="Automation name", min_length=1, max_length=100)
    enabled: bool | None = Field(None, description="Whether the automation is enabled")
    rule_logic: str | None = Field(None, description="How rules combine: 'or' or 'and'")
    rules: List[RuleSchema] | None = Field(None, description="List of rules")
    scene_preset_id: str | None = Field(None, description="Scene preset to activate")
    deactivation_mode: str | None = Field(None, description="'none', 'revert', or 'fallback_scene'")
    deactivation_scene_preset_id: str | None = Field(
        None, description="Scene preset for fallback deactivation"
    )
    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. Empty/null inherits the channel accent.",
    )


class AutomationResponse(BaseModel):
    """Automation information response."""

    id: str = Field(description="Automation ID")
    name: str = Field(description="Automation name")
    enabled: bool = Field(description="Whether the automation is enabled")
    rule_logic: str = Field(description="Rule combination logic")
    rules: List[RuleSchema] = Field(description="List of rules")
    scene_preset_id: str | None = Field(None, description="Scene preset to activate")
    deactivation_mode: str = Field(default="none", description="Deactivation behavior")
    deactivation_scene_preset_id: str | None = Field(None, description="Fallback scene preset")
    tags: List[str] = Field(default_factory=list, description="User-defined tags")
    webhook_url: str | None = Field(
        None, description="Webhook URL for the first webhook rule (if any)"
    )
    is_active: bool = Field(default=False, description="Whether the automation is currently active")
    last_activated_at: datetime | None = Field(
        None, description="Last time this automation was activated"
    )
    last_deactivated_at: datetime | None = Field(
        None, description="Last time this automation was deactivated"
    )
    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. Empty/null inherits the channel accent.",
    )
    created_at: datetime = Field(description="Creation timestamp")
    updated_at: datetime = Field(description="Last update timestamp")


class AutomationListResponse(BaseModel):
    """List of automations response."""

    automations: List[AutomationResponse] = Field(description="List of automations")
    count: int = Field(description="Number of automations")
