from __future__ import annotations

import os
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_dir = Path(__file__).resolve().parents[3]
        if root is not None:
            self._root = root
            return
        profile = os.getenv("DOC_RULES_PROFILE", "legacy").strip().lower()
        if profile == "legacy":
            self._root = base_dir / "doc_rules"
            return
        self._root = base_dir / "doc_rules_v2"

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

    def load(self) -> DocRulesBundle:
        bundle = self._load_from_root(self._root)
        if bundle.supported_doc_types:
            return bundle
        # Safe fallback for quick rollback or incomplete v2 setup.
        fallback = self._root.parent / "doc_rules"
        if fallback != self._root:
            fallback_bundle = self._load_from_root(fallback)
            if fallback_bundle.supported_doc_types:
                return fallback_bundle
        return bundle

    def _load_from_root(self, root: Path) -> DocRulesBundle:
        artifact_rules = self._read_folder(root / "artifact-types", suffix=".md")
        if not artifact_rules:
            artifact_rules = self._read_folder(root / "types", suffix=".md")
        sections = self._read_folder(root / "sections", suffix=".md")
        if not sections:
            sections = self._read_folder(root / "common-elements", suffix=".md")
        return DocRulesBundle(
            documentation_rules=self._read_file(root / "documentation-rules.md"),
            global_rules=self._read_folder(root / "global", suffix=".md"),
            artifact_rules=artifact_rules,
            templates=self._read_templates(root / "templates"),
            sections=sections,
        )

    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 ""
