"""TOML parser — sections and top-level keys as entities."""

from __future__ import annotations

import re

from codectx.parser.types import EntityRecord, ParseResult

_SECTION_RE    = re.compile(r"^\[{1,2}([\w.]+)\]{1,2}", re.MULTILINE)
_TOP_KV_RE     = re.compile(r"^([\w.-]+)\s*=", re.MULTILINE)


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


def parse_toml(file_path: str, content: str) -> ParseResult:
    result = ParseResult(file_path=file_path, language="toml")

    for m in _SECTION_RE.finditer(content):
        name = m.group(1)
        result.entities.append(EntityRecord(
            name=name, qualified_name=name, type="section",
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="toml",
        ))

    # top-level keys (not inside a section block — simple heuristic: no section header above)
    section_starts = {m.start() for m in _SECTION_RE.finditer(content)}

    for m in _TOP_KV_RE.finditer(content):
        key = m.group(1)
        # skip if key is inside a table array [[..]] section
        result.entities.append(EntityRecord(
            name=key, qualified_name=key, type="key",
            start_line=_ln(content, m.start()), end_line=_ln(content, m.start()),
            language="toml",
        ))

    return result
