from __future__ import annotations

from pathlib import Path

from app.core.agent.processes.v2.workflows.doc_update_from_feature.doc_rules_pipeline.models import DocRulesBundle


class DocRulesLoader:
    def __init__(self, root: Path | None = None) -> None:
        base = root or (Path(__file__).resolve().parents[3] / "doc_rules")
        self._root = base

    @property
    def root(self) -> Path:
        return self._root

    def load(self) -> DocRulesBundle:
        return DocRulesBundle(
            documentation_rules=self._read_file(self._root / "documentation-rules.md"),
            global_rules=self._read_folder(self._root / "global", suffix=".md"),
            artifact_rules=self._read_folder(self._root / "artifact-types", suffix=".md"),
            templates=self._read_templates(self._root / "templates"),
            sections=self._read_folder(self._root / "sections", suffix=".md"),
        )

    def _read_templates(self, folder: Path) -> dict[str, str]:
        data: dict[str, str] = {}
        if not folder.exists() or not folder.is_dir():
            return data
        for path in sorted(folder.glob("*.template.md")):
            key = path.name[: -len(".template.md")]
            data[key] = self._safe_read(path)
        return data

    def _read_folder(self, folder: Path, suffix: str) -> dict[str, str]:
        data: dict[str, str] = {}
        if not folder.exists() or not folder.is_dir():
            return data
        for path in sorted(folder.glob(f"*{suffix}")):
            data[path.stem] = self._safe_read(path)
        return data

    def _read_file(self, path: Path) -> str:
        return self._safe_read(path) if path.exists() and path.is_file() else ""

    def _safe_read(self, path: Path) -> str:
        try:
            return path.read_text(encoding="utf-8")
        except Exception:
            return ""
