"""
Configurazione worker – legge le stesse variabili d'ambiente del backend.
"""

from functools import lru_cache

from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


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

    # ── Ambiente ──────────────────────────────────────────────────────────────
    app_env: str = "development"
    log_level: str = "INFO"

    # ── Database ──────────────────────────────────────────────────────────────
    database_url: str = "postgresql+asyncpg://pecflow:pecflow_dev_password@db:5432/pecflow"

    # ── Redis ─────────────────────────────────────────────────────────────────
    redis_url: str = "redis://redis:6379/0"

    # ── MinIO ─────────────────────────────────────────────────────────────────
    minio_endpoint: str = "minio:9000"
    minio_access_key: str = "minioadmin"
    minio_secret_key: str = "minioadmin"
    minio_bucket: str = "pecflow"
    minio_use_ssl: bool = False

    # ── Cifratura credenziali (ADR-002) ───────────────────────────────────────
    encryption_key: str = "0" * 64

    # ── Parametri IMAP sync ───────────────────────────────────────────────────
    imap_idle_timeout_seconds: int = 1680      # 28 minuti (RFC 2177 ≤ 29 min)
    imap_polling_interval_seconds: int = 60   # polling se IDLE non supportato
    imap_max_fetch_per_cycle: int = 50         # max messaggi per ciclo di fetch
    imap_max_error_count: int = 5             # errori consecutivi → status=error
    imap_connect_timeout_seconds: int = 30    # timeout connessione iniziale

    # ── Backoff esponenziale ──────────────────────────────────────────────────
    backoff_initial_seconds: float = 1.0
    backoff_multiplier: float = 2.0
    backoff_max_seconds: float = 300.0        # 5 minuti massimo

    @field_validator("encryption_key")
    @classmethod
    def validate_encryption_key(cls, v: str) -> str:
        if len(v) != 64:
            raise ValueError("ENCRYPTION_KEY deve essere 64 caratteri hex")
        bytes.fromhex(v)
        return v

    @property
    def encryption_key_bytes(self) -> bytes:
        return bytes.fromhex(self.encryption_key)


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