from __future__ import annotations

from app.modules.rag.indexing.docs.models import ParsedDocument, ParsedSubsection, ParsedTopLevelSection


class DocsContentParser:
    def parse(self, frontmatter: dict, body: str, *, fallback_title: str) -> ParsedDocument:
        top_sections = self._top_level_sections(body)
        summary = self._section_text(top_sections, "Summary")
        details = self._section_text(top_sections, "Details")
        title = str(frontmatter.get("title") or "").strip() or fallback_title
        detail_sections = self._subsections(details)
        return ParsedDocument(
            frontmatter=frontmatter,
            title=title,
            summary=summary,
            details=details,
            body=body.strip(),
            detail_sections=detail_sections,
        )

    def _top_level_sections(self, body: str) -> list[ParsedTopLevelSection]:
        sections: list[ParsedTopLevelSection] = []
        current_title = ""
        current_lines: list[str] = []
        for line in body.splitlines():
            if line.startswith("# "):
                if current_title:
                    sections.append(ParsedTopLevelSection(current_title, "\n".join(current_lines).strip()))
                current_title = line[2:].strip()
                current_lines = []
                continue
            current_lines.append(line)
        if current_title:
            sections.append(ParsedTopLevelSection(current_title, "\n".join(current_lines).strip()))
        return sections

    def _section_text(self, sections: list[ParsedTopLevelSection], title: str) -> str:
        for section in sections:
            if section.title.strip().lower() == title.lower():
                return section.content.strip()
        return ""

    def _subsections(self, text: str) -> list[ParsedSubsection]:
        sections: list[ParsedSubsection] = []
        current_title = ""
        current_lines: list[str] = []
        for line in text.splitlines():
            if line.startswith("## "):
                if current_title:
                    sections.append(ParsedSubsection(current_title, "\n".join(current_lines).strip()))
                current_title = line[3:].strip()
                current_lines = []
                continue
            current_lines.append(line)
        if current_title:
            sections.append(ParsedSubsection(current_title, "\n".join(current_lines).strip()))
        return sections
