from __future__ import annotations

import re


class RequirementSourceSections:
    _HEADING_RE = re.compile(r"^(#{2,6})\s+(.+?)\s*$")

    def extract(self, text: str) -> dict[str, str]:
        sections: dict[str, str] = {}
        current_key = ""
        current_level = 0
        current_lines: list[str] = []
        for raw in text.splitlines():
            heading = self._match_heading(raw)
            if heading:
                level, title = heading
                if current_key and level <= current_level:
                    sections[current_key] = "\n".join(current_lines).strip()
                    current_key = ""
                    current_lines = []
                normalized = self._normalize(title)
                if level >= 3:
                    if current_key:
                        sections[current_key] = "\n".join(current_lines).strip()
                    current_key = normalized
                    current_level = level
                    current_lines = []
                    continue
            if current_key:
                current_lines.append(raw)
        if current_key:
            sections[current_key] = "\n".join(current_lines).strip()
        return sections

    def find_for_title(self, sections: dict[str, str], title: str) -> str:
        normalized = self._normalize(title)
        if normalized in sections:
            return sections[normalized]
        for key, value in sections.items():
            if key.startswith(normalized) or normalized.startswith(key):
                return value
        return ""

    def _match_heading(self, raw: str) -> tuple[int, str] | None:
        match = self._HEADING_RE.match(raw.strip())
        if not match:
            return None
        return len(match.group(1)), match.group(2).strip()

    def _normalize(self, value: str) -> str:
        text = value.lower().replace("ё", "е")
        text = text.replace("контракт метода", "контракт")
        text = text.replace("технический use case (тезисно)", "технический use case")
        text = re.sub(r"[^a-zа-я0-9]+", " ", text)
        return re.sub(r"\s+", " ", text).strip()
