from __future__ import annotations

import os
from pathlib import Path

from tests.pipeline_setup.env_loader import load_pipeline_setup_env


class PipelineEnvLoader:
    def __init__(self, test_root: Path) -> None:
        self._test_root = test_root

    def load(self) -> list[Path]:
        loaded: list[Path] = []
        test_env_path = self._test_root / ".env.test"
        if test_env_path.is_file():
            self._apply_file(test_env_path)
            loaded.append(test_env_path)
        loaded.extend(load_pipeline_setup_env(start_dir=self._test_root))
        return loaded

    def _apply_file(self, 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] = self._normalize_value(raw_value.strip())

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