"""Minimal YAML frontmatter parsing and string utilities.

Parses the ``---``-delimited frontmatter block at the top of Markdown
files used for initiative definitions.  Stdlib only.
"""

import re
from pathlib import Path
from typing import Dict, List, Optional


def read_frontmatter(md_path: Path) -> Dict[str, str]:
    """Return key-value pairs from a ``---``-delimited YAML frontmatter block."""
    try:
        txt = md_path.read_text(encoding="utf-8")
    except Exception:
        return {}
    lines = txt.splitlines()
    if not lines or lines[0].strip() != "---":
        return {}
    fm: Dict[str, str] = {}
    for i in range(1, len(lines)):
        if lines[i].strip() == "---":
            break
        m = re.match(r"^\s*([A-Za-z0-9_\-]+)\s*:\s*(.*?)\s*$", lines[i])
        if m:
            fm[m.group(1).strip()] = m.group(2).strip()
    return fm


def parse_bool(v: Optional[str]) -> bool:
    """Interpret a frontmatter value as a boolean (``true``/``yes``/``1``)."""
    if v is None:
        return False
    return v.strip().lower() in ("true", "yes", "1")


def strip_quotes(s: str) -> str:
    """Remove matched surrounding single or double quotes."""
    if len(s) >= 2 and s[0] == s[-1] and s[0] in ('"', "'"):
        return s[1:-1]
    return s


def parse_deps(val: str) -> List[str]:
    """Parse a dependency list like ``[a, b]`` into a Python list of strings."""
    val = val.strip()
    if not val or val in ("[]", "null", "~"):
        return []
    if val.startswith("[") and val.endswith("]"):
        val = val[1:-1]
    return [x.strip() for x in val.split(",") if x.strip()]
