from __future__ import annotations

from dataclasses import dataclass

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.models import RuleDocument


@dataclass(slots=True)
class RulesCatalog:
    by_name: dict[str, str]

    @classmethod
    def from_documents(cls, rules: list[RuleDocument]) -> "RulesCatalog":
        return cls(by_name={item.name: item.content for item in rules})

    def template_text(self, doc_type: str) -> str:
        return self.by_name.get(f"templates/{doc_type}.template.md", "")

    def section_text(self, rule_path: str) -> str:
        return self.by_name.get(rule_path, "")

    def global_text(self) -> str:
        parts: list[str] = []
        documentation_rules = self.by_name.get("documentation-rules.md", "").strip()
        if documentation_rules:
            parts.append("## documentation-rules.md")
            parts.append(documentation_rules)
        for name in sorted(self.by_name):
            if not name.startswith("global/"):
                continue
            value = self.by_name.get(name, "").strip()
            if not value:
                continue
            parts.append(f"## {name}")
            parts.append(value)
        return "\n\n".join(parts).strip()
