from pathlib import Path
import os


class DocsExamplesLoader:
    def __init__(self, prompts_dir: Path | None = None) -> None:
        base = prompts_dir or Path(__file__).resolve().parents[2] / "prompts"
        env_override = os.getenv("AGENT_PROMPTS_DIR", "").strip()
        root = Path(env_override) if env_override else base
        self._examples_dir = root / "docs_examples"

    def load_bundle(self, *, max_files: int = 6, max_chars_per_file: int = 1800) -> str:
        if not self._examples_dir.is_dir():
            return ""
        files = sorted(
            [p for p in self._examples_dir.iterdir() if p.is_file() and p.suffix.lower() in {".md", ".txt"}],
            key=lambda p: p.name.lower(),
        )[:max_files]
        chunks: list[str] = []
        for path in files:
            content = path.read_text(encoding="utf-8", errors="ignore").strip()
            if not content:
                continue
            excerpt = content[:max_chars_per_file].strip()
            chunks.append(f"### Example: {path.name}\n{excerpt}")
        return "\n\n".join(chunks).strip()
