from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path


def _load_env_file() -> None:
    path = Path(os.environ.get("PATANISCAI_ENV_FILE", ".env"))
    if not path.is_file():
        return
    for raw in path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        os.environ.setdefault(key.strip(), value.strip())


def _integer(name: str, default: int, minimum: int, maximum: int) -> int:
    try:
        value = int(os.environ.get(name, str(default)))
    except ValueError as exc:
        raise RuntimeError(f"{name} tem de ser inteiro") from exc
    return max(minimum, min(maximum, value))


@dataclass(frozen=True)
class Settings:
    token: str
    allowed_ips: frozenset[str]
    ollama_url: str
    model: str
    request_timeout: int
    max_files: int
    max_file_bytes: int

    @classmethod
    def from_env(cls) -> "Settings":
        _load_env_file()
        token = os.environ.get("PATANISCAI_TOKEN", "").strip()
        allowed = frozenset(
            item.strip()
            for item in os.environ.get("PATANISCAI_ALLOWED_IPS", "127.0.0.1").split(",")
            if item.strip()
        )
        return cls(
            token=token,
            allowed_ips=allowed,
            ollama_url=os.environ.get("PATANISCAI_OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/"),
            model=os.environ.get("PATANISCAI_MODEL", "AuditAid/PaddleOCR-VL-1.6-0.9B:latest"),
            request_timeout=_integer("PATANISCAI_REQUEST_TIMEOUT", 45, 5, 120),
            max_files=_integer("PATANISCAI_MAX_FILES", 20, 1, 50),
            max_file_bytes=_integer("PATANISCAI_MAX_FILE_BYTES", 15 * 1024 * 1024, 1024, 50 * 1024 * 1024),
        )

