import os
from pathlib import Path


def load_env_file(base_dir):
    """Load a small KEY=VALUE env file without an extra dependency.

    Existing OS environment values always win. Production deployments can ignore
    this helper and provide variables through the service/container environment.
    """
    base_dir = Path(base_dir)
    explicit = os.environ.get("HRPAY_ENV_FILE", "").strip()
    candidates = [Path(explicit).expanduser()] if explicit else [base_dir / ".env.local"]
    for path in candidates:
        if not path.is_file():
            continue
        for raw in path.read_text(encoding="utf-8").splitlines():
            line = raw.strip().lstrip("\ufeff")
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, value = line.split("=", 1)
            key = key.strip()
            value = value.strip()
            if not key:
                continue
            if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
                value = value[1:-1]
            os.environ.setdefault(key, value)
        break
