from typing import Any

from pydantic import model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    database_url: str
    secret_key: str

    app_name: str = "Hermes API"
    app_version: str = "0.1.0"
    access_token_expire_minutes: int = 60
    jwt_issuer: str = "hermes"
    log_level: str = "INFO"
    initial_admin_username: str | None = None
    initial_admin_email: str | None = None
    initial_admin_password: str | None = None
    initial_admin_first_name: str = ""
    initial_admin_last_name: str = ""
    storage_provider: str = "local"
    storage_base_path: str = "/data/storage"
    storage_max_upload_mb: int = 50
    knowledge_storage_path: str = "/data/knowledge"
    knowledge_max_upload_mb: int = 50
    olympus_repair_intake_token: str | None = None
    public_repair_status_base_url: str | None = None
    smtp_host: str | None = None
    smtp_port: int = 587
    smtp_username: str | None = None
    smtp_password: str | None = None
    smtp_from_email: str | None = None
    smtp_from_name: str = "Funktechnik Schubert"
    smtp_use_tls: bool = True

    model_config = SettingsConfigDict(
        env_file=".env",
        extra="ignore",
    )

    @model_validator(mode="before")
    @classmethod
    def apply_legacy_storage_settings(cls, values: Any) -> Any:
        if not isinstance(values, dict):
            return values

        if "storage_base_path" not in values and "knowledge_storage_path" in values:
            values["storage_base_path"] = values["knowledge_storage_path"]

        if "storage_max_upload_mb" not in values and "knowledge_max_upload_mb" in values:
            values["storage_max_upload_mb"] = values["knowledge_max_upload_mb"]

        return values


settings = Settings()
