from __future__ import annotations

import re

from app.core.rag.indexing.docs.chunkers.markdown_chunker import SectionChunk
from app.core.rag.indexing.docs.models import ParsedDocument, ParsedSubsection


class DocsContentParser:
    def parse(self, frontmatter: dict, body: str, *, fallback_title: str, sections: list[SectionChunk]) -> ParsedDocument:
        summary = self._summary(sections)
        detail_sections = self._detail_sections(sections)
        details = "\n\n".join(section.content for section in detail_sections).strip()
        title = str(frontmatter.get("title") or "").strip() or self._title_from_body(body) or fallback_title
        return ParsedDocument(
            frontmatter=frontmatter,
            title=title,
            summary=summary,
            details=details,
            body=body.strip(),
            detail_sections=detail_sections,
        )

    def _summary(self, sections: list[SectionChunk]) -> str:
        for section in sections:
            if section.section_title.strip().lower() == "summary":
                return section.content.strip()
        return ""

    def _detail_sections(self, sections: list[SectionChunk]) -> list[ParsedSubsection]:
        result = [
            ParsedSubsection(
                title=section.section_title,
                content=section.content,
                path=section.section_path,
            )
            for section in sections
            if self._is_details_child(section.section_path)
        ]
        if result:
            return result
        return [
            ParsedSubsection(
                title=section.section_title,
                content=section.content,
                path=section.section_path,
            )
            for section in sections
            if section.section_title.strip().lower() != "summary"
        ]

    def _is_details_child(self, section_path: str) -> bool:
        parts = [item.strip() for item in section_path.split(" > ") if item.strip()]
        for index, part in enumerate(parts):
            if part.lower() == "details" and len(parts) == index + 2:
                return True
        return False

    def _title_from_body(self, body: str) -> str:
        match = re.search(r"^#\s+(.+)$", body, flags=re.MULTILINE)
        return match.group(1).strip() if match else ""
