from __future__ import annotations

import os
from pathlib import Path

_ENV_FILES = (".env", ".env.local")


def load_workspace_env(start_dir: str | Path | None = None) -> list[Path]:
    base = Path(start_dir or Path.cwd()).resolve()
    loaded: list[Path] = []
    for directory in reversed((base, *base.parents)):
        for file_name in _ENV_FILES:
            path = directory / file_name
            if not path.is_file():
                continue
            _load_env_file(path)
            loaded.append(path)
    return loaded


def _load_env_file(path: Path) -> None:
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, raw_value = line.split("=", 1)
        name = key.removeprefix("export ").strip()
        if not name or name in os.environ:
            continue
        os.environ[name] = _normalize_value(raw_value.strip())


def _normalize_value(value: str) -> str:
    if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
        return value[1:-1]
    return value
