import re
from typing import Any

import yaml  # type: ignore[import-untyped]

_FRONTMATTER_RE = re.compile(r"^---\s*\r?\n(.*?)\r?\n?---\s*\r?\n?", re.DOTALL)


def parse(content: str) -> tuple[dict[str, Any], str]:
    """Parse YAML frontmatter from Markdown content.

    Returns (metadata_dict, body_string). If no frontmatter is found,
    returns ({}, full_content).
    """
    if not content:
        return {}, content

    m = _FRONTMATTER_RE.match(content)
    if not m:
        return {}, content

    raw_meta = yaml.safe_load(m.group(1))
    # yaml.safe_load returns None for an empty block — treat that as empty dict.
    # For non-None, non-dict values (e.g. a bare string from a `---` divider that
    # isn't actually frontmatter), fall back to returning the full content unparsed
    # so callers always receive a dict and see the original text in the body.
    if raw_meta is None:
        return {}, content[m.end() :]
    if not isinstance(raw_meta, dict):
        return {}, content

    body = content[m.end() :]
    return raw_meta, body


def dump(meta: dict[str, Any], body: str) -> str:
    """Serialize metadata and body back to a frontmatter Markdown string."""
    if not meta:
        return body
    fm = yaml.dump(meta, default_flow_style=False, allow_unicode=True).strip()
    return f"---\n{fm}\n---\n{body}"
