import re
from typing import List, Optional, Tuple

# (section_title, heading_level, body_content)
ParsedSection = Tuple[str, int, str]


class MarkdownParser:
    """Splits markdown content into sections based on ATX-style headings (# H1 … ###### H6)."""

    _HEADING_RE = re.compile(r"^(#{1,6})\s+(.+)", re.MULTILINE)

    def parse_sections(self, content: str) -> List[ParsedSection]:
        """
        Returns a list of (title, level, body) tuples.
        Content before the first heading is captured as an 'Introduction' section.
        """
        lines = content.split("\n")
        sections: List[ParsedSection] = []
        current_heading: Optional[str] = None
        current_level: int = 0
        current_lines: List[str] = []

        for line in lines:
            match = self._HEADING_RE.match(line)
            if match:
                # Flush previous section
                if current_heading is not None:
                    sections.append(
                        (current_heading, current_level, "\n".join(current_lines).strip())
                    )
                elif current_lines:
                    body = "\n".join(current_lines).strip()
                    if body:
                        sections.append(("Introduction", 0, body))

                current_heading = match.group(2).strip()
                current_level = len(match.group(1))
                current_lines = []
            else:
                current_lines.append(line)

        # Flush last section
        if current_heading is not None:
            sections.append(
                (current_heading, current_level, "\n".join(current_lines).strip())
            )
        elif current_lines:
            body = "\n".join(current_lines).strip()
            if body:
                sections.append(("Introduction", 0, body))

        return sections
