from __future__ import annotations

from dataclasses import dataclass
from dataclasses import field


@dataclass(slots=True)
class DocRulesBundle:
    documentation_rules: str = ""
    global_rules: dict[str, str] = field(default_factory=dict)
    artifact_rules: dict[str, str] = field(default_factory=dict)
    templates: dict[str, str] = field(default_factory=dict)
    sections: dict[str, str] = field(default_factory=dict)

    @property
    def supported_doc_types(self) -> set[str]:
        return set(self.artifact_rules.keys()) & set(self.templates.keys())

    def has_doc_type(self, doc_type: str) -> bool:
        return doc_type in self.supported_doc_types

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


@dataclass(slots=True)
class SelectedDocRules:
    doc_type: str
    global_text: str
    artifact_text: str
    template_text: str
    section_texts: dict[str, str] = field(default_factory=dict)

    def render_for_prompt(self) -> str:
        parts: list[str] = []
        if self.global_text.strip():
            parts.append("## Global rules")
            parts.append(self.global_text.strip())
        if self.artifact_text.strip():
            parts.append(f"## Artifact rules ({self.doc_type})")
            parts.append(self.artifact_text.strip())
        if self.template_text.strip():
            parts.append(f"## Template ({self.doc_type})")
            parts.append(self.template_text.strip())
        for name in sorted(self.section_texts.keys()):
            text = self.section_texts.get(name, "").strip()
            if not text:
                continue
            parts.append(f"## Section rule: {name}")
            parts.append(text)
        return "\n\n".join(parts).strip()
