"""Application settings loaded from environment variables."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from pydantic import field_validator
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """Configuration for edinet-mcp.

    Values are read from environment variables or a `.env` file.
    """

    edinet_api_key: str = ""
    edinet_base_url: str = "https://api.edinet-fsa.go.jp/api/v2"
    cache_dir: Path = Path.home() / ".cache" / "edinet-mcp"
    rate_limit_rps: float = 0.5  # requests per second (conservative default)
    request_timeout: float = 30.0
    max_retries: int = 3  # retries on 429/5xx/timeout

    model_config = {"env_prefix": "", "env_file": ".env", "extra": "ignore"}

    @field_validator("edinet_base_url")
    @classmethod
    def _validate_base_url(cls, v: str) -> str:
        if not v.startswith(("https://", "http://localhost")):
            msg = "edinet_base_url must use HTTPS (or http://localhost for testing)"
            raise ValueError(msg)
        return v


def get_settings(**overrides: Any) -> Settings:
    """Create a Settings instance, allowing programmatic overrides."""
    return Settings(**overrides)
