"""Configuration loaded from environment variables with sensible defaults."""

from __future__ import annotations

import os
from dataclasses import dataclass, field


def _env(key: str, default: str = "") -> str:
    return os.environ.get(key, default)


@dataclass(frozen=True)
class ScheduledEmailConfig:
    base_url: str = field(default_factory=lambda: _env("SCHEDMAIL_BASE_URL", "https://example.com/login?token="))
    rotate_hours: float = field(default_factory=lambda: float(_env("SCHEDMAIL_ROTATE_HOURS", "24")))
    sct: str = field(default_factory=lambda: _env("SCHEDMAIL_SCT", "*****-daiju"))

    smtp_host: str = field(default_factory=lambda: _env("SCHEDMAIL_SMTP_HOST", "smtp.163.com"))
    smtp_port: int = field(default_factory=lambda: int(_env("SCHEDMAIL_SMTP_PORT", "465")))
    smtp_user: str = field(default_factory=lambda: _env("SCHEDMAIL_SMTP_USER", ""))
    smtp_pass: str = field(default_factory=lambda: _env("SCHEDMAIL_SMTP_PASS", ""))

    recipient: str = field(default_factory=lambda: _env("SCHEDMAIL_RECIPIENT", ""))
    mask_secret: bool = field(default_factory=lambda: _env("SCHEDMAIL_MASK_SECRET", "false").lower() == "true")

    def validate(self) -> None:
        """Raise ``ValueError`` if required credentials are missing."""
        missing = [
            name
            for name, val in (
                ("SCHEDMAIL_SMTP_USER", self.smtp_user),
                ("SCHEDMAIL_SMTP_PASS", self.smtp_pass),
                ("SCHEDMAIL_RECIPIENT", self.recipient),
            )
            if not val
        ]
        if missing:
            raise ValueError(
                f"Required config not set: {', '.join(missing)}. "
                "Set them via environment variables or pass a ScheduledEmailConfig."
            )
