from __future__ import annotations

from pathlib import Path


def _parse_dotenv(text: str) -> dict[str, str]:
    env: dict[str, str] = {}
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip()
        if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
            value = value[1:-1]
        if key:
            env[key] = value
    return env


def load_dotenv(path: str | Path = ".env") -> dict[str, str]:
    """
    Load a minimal .env file (KEY=VALUE lines).

    Returns parsed values. Does not mutate os.environ; callers decide precedence.
    """
    dotenv_path = Path(path)
    if not dotenv_path.exists():
        return {}
    return _parse_dotenv(dotenv_path.read_text(encoding="utf-8"))

