from pathlib import Path
import os

import yaml


class PromptLoader:
    def __init__(self, prompts_path: Path | None = None) -> None:
        base = prompts_path or Path(__file__).resolve().parent / "prompts.yml"
        env_override = os.getenv("AGENT_PROMPTS_DIR", "").strip()
        raw_path = Path(env_override) if env_override else base
        self._path = raw_path / "prompts.yml" if raw_path.is_dir() else raw_path
        self._prompts = self._load_prompts()

    def load(self, name: str) -> str:
        return str(self._prompts.get(name, "") or "").strip()

    def _load_prompts(self) -> dict[str, str]:
        if not self._path.is_file():
            return {}
        payload = yaml.safe_load(self._path.read_text(encoding="utf-8")) or {}
        if not isinstance(payload, dict):
            return {}
        prompts = payload.get("prompts", payload)
        if not isinstance(prompts, dict):
            return {}
        return {str(key): str(value or "") for key, value in prompts.items()}
