"""Matcher DSL: public API facade."""

from __future__ import annotations

import re

from db_test_helpers.core._matcher_types import (
    AndMatcher,
    AnyMatcher,
    EqMatcher,
    GtMatcher,
    LtMatcher,
    Matcher,
    NotMatcher,
    OrMatcher,
)
from db_test_helpers.core._parser import parse

__all__ = [
    "AndMatcher",
    "AnyMatcher",
    "EqMatcher",
    "GtMatcher",
    "LtMatcher",
    "Matcher",
    "NotMatcher",
    "OrMatcher",
    "is_dsl_string",
    "is_var_dsl",
    "parse_matcher",
    "resolve_var",
]

_DSL_PATTERN = re.compile(r"^\$([a-z]+)\(")
_VAR_PATTERN = re.compile(r"^\$var\(([^)]+)\)$")


def is_dsl_string(value: object) -> bool:
    if not isinstance(value, str):
        return False
    return _DSL_PATTERN.match(value) is not None


def is_var_dsl(value: object) -> bool:
    if not isinstance(value, str):
        return False
    return _VAR_PATTERN.match(value) is not None


def resolve_var(value: str, variables: dict[str, object]) -> object:
    m = _VAR_PATTERN.match(value)
    if m is None:
        raise ValueError(f"Not a $var() expression: {value!r}")
    name = m.group(1).strip()
    if name not in variables:
        raise ValueError(f"Undefined variable: {name!r}")
    return variables[name]


def parse_matcher(value: str, variables: dict[str, object]) -> Matcher:
    return parse(value, variables)
