from __future__ import annotations

import logging
import re

import yaml

LOGGER = logging.getLogger(__name__)


class DocsFrontmatterParser:
    def split(self, content: str) -> tuple[dict, str]:
        if not content.startswith("---\n"):
            return {}, content
        parts = content.split("---", 2)
        if len(parts) < 3:
            return {}, content
        _, raw, body = parts
        try:
            payload = yaml.safe_load(raw) or {}
            if isinstance(payload, dict):
                return payload, body.strip()
        except yaml.YAMLError as exc:
            LOGGER.warning("docs frontmatter parse warning: reason=%s", exc.__class__.__name__)
        payload = self._fallback(raw)
        payload["__frontmatter_parse_error__"] = True
        return payload, body.strip()

    def _fallback(self, raw: str) -> dict:
        payload: dict[str, object] = {}
        for line in raw.splitlines():
            text = line.strip()
            if not text or text.startswith("#"):
                continue
            match = re.match(r"^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$", text)
            if not match:
                continue
            key = match.group(1)
            value = match.group(2).strip()
            if not value:
                continue
            if value == "[]":
                payload[key] = []
                continue
            if value == "{}":
                payload[key] = {}
                continue
            payload[key] = value.strip("'\"")
        return payload
