from __future__ import annotations

import os
from pathlib import Path

from app.modules.shared.env_loader import load_workspace_env


def load_pipeline_setup_env(start_dir: str | Path | None = None) -> list[Path]:
    base = Path(start_dir or Path.cwd()).resolve()
    loaded = load_workspace_env(start_dir=base)
    pipeline_root = _find_pipeline_setup_root(base)
    env_path = pipeline_root / ".env"
    if env_path.is_file():
        _apply_env_file(env_path)
        loaded.append(env_path)
    return loaded


def _find_pipeline_setup_root(base: Path) -> Path:
    for directory in (base, *base.parents):
        if directory.name == "pipeline_setup" and (directory / "__init__.py").is_file():
            return directory
    raise RuntimeError(f"Unable to locate tests/pipeline_setup root from: {base}")


def _apply_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:
            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
