"""CITATION.cff loading for Accountable Record identity checks.

WHY: CITATION.cff is YAML, but stage 010 only needs a small set of top-level
scalar fields. This parser intentionally avoids adding a YAML dependency for
identity validation.
"""

from dataclasses import dataclass
from pathlib import Path

from accountable_record.stage_010_identity.base.constants import CITATION_FILENAME


@dataclass(frozen=True)
class CitationIdentity:
    """Identity fields read from CITATION.cff."""

    title: str | None
    version: str | None
    date_released: str | None
    raw_scalars: dict[str, str]


def read_citation_identity(repo_root: Path) -> CitationIdentity:
    """Read selected top-level scalar fields from CITATION.cff."""
    path = repo_root / CITATION_FILENAME
    if not path.is_file():
        msg = f"Missing required file: {path}"
        raise FileNotFoundError(msg)

    scalars = _read_top_level_scalars(path)

    return CitationIdentity(
        title=scalars.get("title"),
        version=scalars.get("version"),
        date_released=scalars.get("date-released"),
        raw_scalars=scalars,
    )


def _read_top_level_scalars(path: Path) -> dict[str, str]:
    """Read simple top-level key/value scalar fields from a CFF file.

    This is not a complete YAML parser. It is sufficient for fields like:

        title: Accountable Record
        version: 0.1.0
        date-released: 2026-05-23

    Nested blocks and lists are ignored.
    """
    scalars: dict[str, str] = {}

    for raw_line in path.read_text(encoding="utf-8").splitlines():
        if not raw_line.strip():
            continue

        if raw_line.lstrip().startswith("#"):
            continue

        if raw_line.startswith((" ", "\t", "-")):
            continue

        if ":" not in raw_line:
            continue

        key, value = raw_line.split(":", 1)
        key = key.strip()
        value = value.strip()

        if not key or not value:
            continue

        scalars[key] = _strip_yaml_quotes(value)

    return scalars


def _strip_yaml_quotes(value: str) -> str:
    """Strip matching single or double quotes from a scalar value."""
    if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
        return value[1:-1]
    return value
