from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path


@dataclass(frozen=True)
class ApiSettings:
    host: str = "127.0.0.1"
    port: int = 8000
    reload: bool = False
    stream_interval_seconds: float = 5.0
    read_cache_ttl_seconds: float = 30.0
    data_root: Path = Path("data")
    microstructure_enabled: bool = True
    cors_origins: tuple[str, ...] = ("http://127.0.0.1:3000", "http://localhost:3000")
    cors_origin_regex: str = (
        r"^https?://("
        r"localhost|"
        r"127\.0\.0\.1|"
        r"0\.0\.0\.0|"
        r"10(?:\.\d{1,3}){3}|"
        r"192\.168(?:\.\d{1,3}){2}|"
        r"172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2}"
        r")(?::\d+)?$"
    )


def get_api_settings() -> ApiSettings:
    cors = os.getenv("UFORIA_API_CORS_ORIGINS")
    return ApiSettings(
        host=os.getenv("UFORIA_API_HOST", "127.0.0.1"),
        port=int(os.getenv("UFORIA_API_PORT", "8000")),
        reload=os.getenv("UFORIA_API_RELOAD", "false").lower() == "true",
        stream_interval_seconds=float(os.getenv("UFORIA_API_STREAM_INTERVAL", "5")),
        read_cache_ttl_seconds=float(os.getenv("UFORIA_API_CACHE_TTL", "30")),
        data_root=Path(os.getenv("UFORIA_DATA_ROOT", "data")),
        microstructure_enabled=os.getenv("UFORIA_ENABLE_MICROSTRUCTURE", "true").lower()
        == "true",
        cors_origins=tuple(
            item.strip()
            for item in (
                cors.split(",") if cors else ["http://127.0.0.1:3000", "http://localhost:3000"]
            )
            if item.strip()
        ),
        cors_origin_regex=os.getenv(
            "UFORIA_API_CORS_ORIGIN_REGEX",
            ApiSettings.cors_origin_regex,
        ),
    )
