from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path


API_URL = "https://www.intecmar.gal/Api/EstadoZonasProducion/EstadoZonasBiotoxinas"


def load_env(env_path: Path) -> dict[str, str]:
    env: dict[str, str] = {}
    if not env_path.is_file():
        return env

    with env_path.open("r", encoding="utf-8") as handle:
        for raw_line in handle:
            line = raw_line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, value = line.split("=", 1)
            value = value.strip()
            if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
                value = value[1:-1]
            env[key.strip()] = value
    return env


@dataclass(frozen=True)
class AppConfig:
    base_dir: Path
    env_path: Path
    log_dir: Path
    log_file: Path
    api_url: str
    env: dict[str, str]


def build_config(base_dir: Path) -> AppConfig:
    env_path = base_dir / ".env"
    log_dir = base_dir / "logs"
    log_dir.mkdir(parents=True, exist_ok=True)
    return AppConfig(
        base_dir=base_dir,
        env_path=env_path,
        log_dir=log_dir,
        log_file=log_dir / "import_situations_api.log",
        api_url=API_URL,
        env=load_env(env_path),
    )
