"""Lightweight .env autoloader for api_sdk.

This module provides a minimal, dependency-free loader that reads key=value
lines from a local ".env" file and injects them into the current process
environment if the variables are not already set.

Notes:
- Supports lines like `KEY=value` or `export KEY=value`.
- Ignores blank lines and lines starting with '#'.
- Strips surrounding single or double quotes from the value if present.
- Never overrides an already-set environment variable.
"""

from __future__ import annotations

import os
from pathlib import Path
from threading import Lock
from typing import Iterable, Union


_loaded = False
_lock = Lock()


def _parse_and_set(line: str) -> None:
    s = line.strip()
    if not s or s.startswith("#"):
        return
    if s.startswith("export "):
        s = s[len("export "):].lstrip()
    if "=" not in s:
        return
    key, val = s.split("=", 1)
    key = key.strip()
    val = val.strip()
    # Strip surrounding quotes
    if (len(val) >= 2) and ((val[0] == val[-1]) and val[0] in ('"', "'")):
        val = val[1:-1]
    if key and key not in os.environ:
        os.environ[key] = val


def load_env_once(path: Union[str, os.PathLike, Iterable[Union[str, os.PathLike]], None] = None) -> bool:
    """Load environment variables from one or more .env files exactly once.

    Accepts:
      - a single path, or
      - an iterable of candidate paths (first existing is used), or
      - None (defaults to ./.env)

    Returns True if any .env file was found and processed, else False.
    """
    global _loaded
    if _loaded:
        return False
    with _lock:
        if _loaded:
            return False
        # Build candidates
        if path is None:
            candidates = [Path(".env")]
        elif isinstance(path, (str, os.PathLike)):
            candidates = [Path(path)]
        else:
            candidates = [Path(p) for p in path]

        for p in candidates:
            try:
                if p.exists() and p.is_file():
                    for line in p.read_text(encoding="utf-8").splitlines():
                        _parse_and_set(line)
                    _loaded = True
                    return True
            except Exception:
                # Fail-safe: never raise from autoload; just skip
                continue
        _loaded = True
        return False


__all__ = ["load_env_once"]
