"""Pydantic settings for environment-based configuration."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Environment-based settings that can override config file values."""

    model_config = SettingsConfigDict(
        env_prefix="CURADISE_",
        env_nested_delimiter="__",
        case_sensitive=False,
        extra="ignore",
    )

    # Server settings
    server_url: str | None = Field(default=None, description="Curadise server URL")
    server_timeout: float = Field(default=30.0, gt=0, le=300)
    server_verify_ssl: bool = True

    # Authentication
    enrollment_token: SecretStr | None = None
    auth_token_file: Path | None = None

    # mTLS
    mtls_cert: Path | None = None
    mtls_key: Path | None = None
    mtls_ca: Path | None = None

    # Logging
    log_level: str = "INFO"
    log_format: str = "json"
    log_file: Path | None = None

    # State directory
    state_dir: Path = Field(default=Path("/var/lib/curadise-agent"))

    # Buffer settings
    buffer_max_size: int = Field(default=10_000, ge=100, le=1_000_000)
    buffer_flush_interval: float = Field(default=5.0, gt=0, le=300)

    # Heartbeat
    heartbeat_interval: float = Field(default=30.0, gt=0, le=3600)

    # Executor
    executor_enabled: bool = True
    executor_require_signature: bool = True

    def to_config_overrides(self) -> dict[str, Any]:
        """Convert settings to nested dict for config override."""
        overrides: dict[str, Any] = {}

        if self.server_url is not None:
            overrides.setdefault("server", {})["url"] = self.server_url
        if self.server_timeout != 30.0:
            overrides.setdefault("server", {})["timeout"] = self.server_timeout
        if not self.server_verify_ssl:
            overrides.setdefault("server", {})["verify_ssl"] = False

        if self.enrollment_token is not None:
            overrides.setdefault("auth", {})["enrollment_token"] = self.enrollment_token
        if self.auth_token_file is not None:
            overrides.setdefault("auth", {})["token_file"] = self.auth_token_file
        if self.mtls_cert is not None:
            overrides.setdefault("auth", {})["mtls_cert"] = self.mtls_cert
        if self.mtls_key is not None:
            overrides.setdefault("auth", {})["mtls_key"] = self.mtls_key
        if self.mtls_ca is not None:
            overrides.setdefault("auth", {})["mtls_ca"] = self.mtls_ca

        if self.log_level != "INFO":
            overrides.setdefault("logging", {})["level"] = self.log_level
        if self.log_format != "json":
            overrides.setdefault("logging", {})["format"] = self.log_format
        if self.log_file is not None:
            overrides.setdefault("logging", {})["file"] = self.log_file

        if self.state_dir != Path("/var/lib/curadise-agent"):
            overrides.setdefault("state", {})["directory"] = self.state_dir

        if self.buffer_max_size != 10_000:
            overrides.setdefault("buffer", {})["max_size"] = self.buffer_max_size
        if self.buffer_flush_interval != 5.0:
            overrides.setdefault("buffer", {})["flush_interval"] = self.buffer_flush_interval

        if self.heartbeat_interval != 30.0:
            overrides.setdefault("heartbeat", {})["interval"] = self.heartbeat_interval

        if not self.executor_enabled:
            overrides.setdefault("executor", {})["enabled"] = False
        if not self.executor_require_signature:
            overrides.setdefault("executor", {})["require_signature"] = False

        return overrides
