from __future__ import annotations

import re

from app.core.rag.indexing.docs.models import ParsedSubsection, WorkflowScenario


class DocsWorkflowExtractor:
    _SECTION_TITLES = {"сценарий", "технический use case"}
    _LABELS = {
        "название": "name",
        "предусловия": "preconditions",
        "триггер": "trigger",
        "основной сценарий": "main_flow",
        "альтернативный сценарий": "alternative_flow",
        "обработка ошибок": "error_handling",
        "постусловие": "postconditions",
    }

    def extract(self, sections: list[ParsedSubsection]) -> list[WorkflowScenario]:
        scenario_section = next(
            (section for section in sections if section.title.strip().lower() in self._SECTION_TITLES),
            None,
        )
        if scenario_section is None or not scenario_section.content.strip():
            return []
        fields = self._fields(scenario_section.content)
        name = fields.get("name", ["Scenario"])[0]
        return [
            WorkflowScenario(
                name=name,
                preconditions=fields.get("preconditions", []),
                trigger=fields.get("trigger", []),
                main_flow=fields.get("main_flow", []),
                alternative_flow=fields.get("alternative_flow", []),
                error_handling=fields.get("error_handling", []),
                postconditions=fields.get("postconditions", []),
                anchor=scenario_section.path,
            )
        ]

    def _fields(self, text: str) -> dict[str, list[str]]:
        fields: dict[str, list[str]] = {}
        current_key: str | None = None
        for raw_line in text.splitlines():
            line = raw_line.strip()
            if not line:
                continue
            if line.startswith("**") and line.endswith("**"):
                label = line.strip("*").rstrip(":").strip().lower()
                current_key = self._LABELS.get(label)
                if current_key is not None:
                    fields.setdefault(current_key, [])
                continue
            if current_key is None:
                continue
            normalized = line
            if normalized.startswith("- "):
                normalized = normalized[2:].strip()
            elif re.match(r"^\d+\.\s+", normalized):
                normalized = re.sub(r"^\d+\.\s+", "", normalized).strip()
            if normalized:
                fields[current_key].append(normalized)
        return fields
