"""Executes a declarative field map against a source record.

The syntax is deliberately tiny: $.a.b and $.a[0]. Anything richer would make
the maps harder for a human to review, and C's LLM authors these configs.
"""
import logging
import re

logger = logging.getLogger(__name__)

_SEGMENT = re.compile(r"\A([A-Za-z_][A-Za-z0-9_]*)((?:\[\d+\])*)\Z")
_INDEX = re.compile(r"\[(\d+)\]")


class FieldMapError(Exception):
    """The field map itself is malformed, as opposed to the data being sparse."""


def resolve_path(record: dict, path):
    if not isinstance(path, str) or not path.startswith("$.") or path == "$.":
        raise FieldMapError(f"malformed path: {path!r}")

    current = record
    for raw in path[2:].split("."):
        m = _SEGMENT.match(raw)
        if not m:
            raise FieldMapError(f"malformed path segment {raw!r} in {path!r}")

        key, indexes = m.group(1), _INDEX.findall(m.group(2))
        if not isinstance(current, dict):
            return None
        current = current.get(key)

        for i in indexes:
            if not isinstance(current, list):
                return None
            idx = int(i)
            current = current[idx] if idx < len(current) else None

    return current


def apply_field_map(record: dict, fields: dict) -> dict:
    return {target: resolve_path(record, path) for target, path in fields.items()}
