from functools import lru_cache
from pathlib import Path

from pydantic import computed_field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    app_name: str = "Home Automation Backend (Python)"
    app_env: str = "production"
    app_debug: bool = False
    app_hostname: str = "localhost:8000"
    app_database_url: str = "sqlite:///./data/app.db"

    ticktick_client_id: str = ""
    ticktick_client_secret: str = ""
    ticktick_token: str = ""

    home_assistant_base_url: str = ""
    home_assistant_auth_token: str = ""
    home_assistant_timeout_seconds: float = 1.0
    home_assistant_action_task_project_id: str = ""
    smtp_enabled: bool = False
    smtp_host: str = ""
    smtp_port: int = 587
    smtp_username: str = ""
    smtp_password: str = ""
    smtp_from_name: str = ""
    smtp_from_address: str = ""
    smtp_to_address: str = ""
    smtp_use_starttls: bool = True
    poo_webhook_id: str = ""
    poo_sensor_entity_name: str = "sensor.test_poo_status"
    poo_sensor_friendly_name: str = "Poo Status"
    auth_bootstrap_username: str = "admin"
    auth_bootstrap_password: str = "admin"
    auth_session_cookie_name: str = "home_automation_session"
    auth_session_ttl_hours: int = 12
    auth_cookie_secure_override: bool | None = True
    auth_login_throttle_enabled: bool = True
    auth_trust_forwarded_for: bool = False
    auth_totp_issuer: str = ""  # defaults to app_name when empty

    # Modbus polling — global kill-switch (CONFIG_FIELDS registered in T08).
    # Off by default: polling is opt-in so a fresh deploy writes no modbus_reading
    # rows until the admin explicitly enables it (matches mqtt/discovery defaults).
    modbus_polling_enabled: bool = False

    # MQTT broker connection (T08 wires into CONFIG_FIELDS/UI; T10 builds the client).
    mqtt_enabled: bool = False
    mqtt_broker_host: str = ""
    mqtt_broker_port: int = 1883
    mqtt_username: str = ""
    mqtt_password: str = ""
    mqtt_tls_enabled: bool = False

    # Home Assistant MQTT Discovery (T08 wires into CONFIG_FIELDS/UI; T11 does publishing).
    ha_discovery_enabled: bool = False
    ha_discovery_prefix: str = "homeassistant"
    # State/availability topics use a separate prefix so they live outside the HA discovery
    # namespace.  HA still receives state via the state_topic declared in the discovery config.
    ha_state_topic_prefix: str = "home_automation"

    # DSMR smart-meter ingest via MQTT (M6; default off — opt-in).
    # Subscribe to dsmr_mqtt_topic when dsmr_ingest_enabled=True.
    dsmr_ingest_enabled: bool = False
    dsmr_mqtt_topic: str = "dsmr/json"
    dsmr_sample_interval_s: int = 10
    # DSMR dual-tariff topic: publishes "1" (dal/off-peak) or "2" (normal/peak).
    # Empty string = do not subscribe (tariff-aware pricing disabled).
    dsmr_tariff_topic: str = "dsmr/meter-stats/electricity_tariff"

    # Tibber dynamic pricing credentials (M6; only used when active contract kind=tibber).
    tibber_api_token: str = ""
    tibber_home_id: str = ""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
    )

    @computed_field
    @property
    def is_development(self) -> bool:
        return self.app_env.lower() == "development"

    @computed_field
    @property
    def app_base_url(self) -> str:
        hostname = self.app_hostname.strip().rstrip("/")
        if not hostname:
            return ""
        scheme = "http" if self.is_development else "https"
        return f"{scheme}://{hostname}"

    @computed_field
    @property
    def ticktick_redirect_uri(self) -> str:
        if not self.app_base_url:
            return ""
        return f"{self.app_base_url}/ticktick/auth/code"

    @staticmethod
    def _sqlite_path_from_url(database_url: str) -> Path | None:
        prefix = "sqlite:///"
        if not database_url.startswith(prefix):
            return None
        raw_path = database_url[len(prefix) :]
        return Path(raw_path)

    @computed_field
    @property
    def app_sqlite_path(self) -> Path | None:
        return self._sqlite_path_from_url(self.app_database_url)

    @computed_field
    @property
    def auth_cookie_secure(self) -> bool:
        if self.auth_cookie_secure_override is not None:
            return self.auth_cookie_secure_override
        return not self.is_development

    @computed_field
    @property
    def effective_totp_issuer(self) -> str:
        """The issuer label shown in Authenticator apps. Falls back to app_name."""
        return self.auth_totp_issuer.strip() or self.app_name


@lru_cache
def get_settings() -> Settings:
    return Settings()
