"""YAML parser — top-level and nested section keys as entities."""

from __future__ import annotations

import re

from codectx.parser.types import EntityRecord, ParseResult

# Capture top-level keys (no leading spaces) and second-level keys (2-space indent)
_TOP_KEY_RE   = re.compile(r"^([\w.-]+)\s*:", re.MULTILINE)
_L2_KEY_RE    = re.compile(r"^  ([\w.-]+)\s*:", re.MULTILINE)


def _ln(content: str, pos: int) -> int:
    return content[:pos].count("\n") + 1


def parse_yaml(file_path: str, content: str) -> ParseResult:
    result = ParseResult(file_path=file_path, language="yaml")

    seen: set[str] = set()
    for m in _TOP_KEY_RE.finditer(content):
        key = m.group(1)
        if key.startswith("#") or key in seen:
            continue
        seen.add(key)
        result.entities.append(EntityRecord(
            name=key, qualified_name=key, type="key",
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="yaml",
        ))

    return result
