import os
from dataclasses import dataclass, field
from functools import lru_cache


def _csv_env(name: str, default: list[str]) -> list[str]:
    raw = os.getenv(name)
    if not raw:
        return default
    return [item.strip() for item in raw.split(",") if item.strip()]


@dataclass(frozen=True)
class Settings:
    app_name: str = os.getenv("APP_NAME", "Certificate Management System")
    app_env: str = os.getenv("APP_ENV", "development")
    database_url: str = os.getenv("DATABASE_URL", "sqlite:///./dev.db")
    secret_key: str = os.getenv("SECRET_KEY", "change-me")
    public_base_url: str = os.getenv("PUBLIC_BASE_URL", "http://localhost:8080")
    certificate_no_secret: str = os.getenv("CERTIFICATE_NO_SECRET", "change-me")
    data_root: str = os.getenv("DATA_ROOT", "/data/certificate-system")
    cors_origins: list[str] = field(
        default_factory=lambda: _csv_env("CORS_ORIGINS", ["http://localhost:5173", "http://localhost:8080"])
    )

    # 短信服务配置
    # local=本地测试（验证码打印到终端），aliyun=阿里云短信
    sms_mode: str = os.getenv("SMS_MODE", "local")
    aliyun_access_key_id: str = os.getenv("ALIYUN_ACCESS_KEY_ID", "")
    aliyun_access_key_secret: str = os.getenv("ALIYUN_ACCESS_KEY_SECRET", "")
    aliyun_sms_sign_name: str = os.getenv("ALIYUN_SMS_SIGN_NAME", "")
    aliyun_sms_template_code: str = os.getenv("ALIYUN_SMS_TEMPLATE_CODE", "")

    # PDF配置
    pdf_cache_days: int = int(os.getenv("PDF_CACHE_DAYS", "30"))
    pdf_cleanup_days: int = int(os.getenv("PDF_CLEANUP_DAYS", "5"))


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


settings = get_settings()
