"""Shared lightweight parser for brief markdown frontmatter."""
from __future__ import annotations

import re
from pathlib import Path
from typing import Mapping


_BRIEF_FRONTMATTER_LINE_RE = re.compile(r"^([a-zA-Z0-9_\-]+)\s*:\s*(.*)$")


def read_brief_frontmatter(path: Path) -> dict[str, str]:
    """Read a brief's YAML-style frontmatter into a flat key-value map.

    Returns ``{}`` if the file is unreadable, has no frontmatter, or the
    frontmatter is malformed. Comments and quoted values are stripped.
    """
    try:
        text = path.read_text(encoding="utf-8")
    except OSError:
        return {}
    if not text.startswith("---"):
        return {}
    lines = text.splitlines()
    if not lines or lines[0].strip() != "---":
        return {}
    out: dict[str, str] = {}
    for line in lines[1:]:
        if line.strip() == "---":
            break
        comment_idx = line.find("#")
        if comment_idx >= 0:
            line = line[:comment_idx]
        match = _BRIEF_FRONTMATTER_LINE_RE.match(line.strip())
        if not match:
            continue
        key, value = match.group(1), match.group(2).strip()
        if (
            len(value) >= 2
            and value[0] == value[-1]
            and value[0] in ("'", '"')
        ):
            value = value[1:-1]
        out[key] = value
    return out


def is_canonical_generated_brief(frontmatter: Mapping[str, str]) -> bool:
    return (
        frontmatter.get("type") == "brief"
        and frontmatter.get("generator") == "okstra-brief-gen"
    )


def has_reporter_confirmation_contract(frontmatter: Mapping[str, str]) -> bool:
    return "reporter-confirmations" in frontmatter
