import re

from brake.exceptions import CircularVariable, UndefinedVariable


class VariableResolver:
    """Recursively resolves variables

    x: plop -> plop
    y: {x}/lala -> plop/kaka

    """

    def __init__(self, variables: dict[str, str]):
        self.variables = variables
        self.resolved: dict[str, str] = {}

    def resolve(self, value: str) -> str:
        if value in self.resolved:
            return self.resolved[value]

        def replace_match(match: re.Match) -> str:
            var_name = match.group(1)
            if var_name not in self.variables:
                raise UndefinedVariable(f"Undefined variable: {var_name}")
            return self.resolve(self.variables[var_name])

        try:
            resolved = re.sub(r"\{(\w+)\}", replace_match, value)
        except RecursionError:
            raise CircularVariable("Circular reference detected")

        self.resolved[value] = resolved
        return resolved
