"""Bounded evaluator for the portable subset of BeamNG value expressions.

BeamNG JBeam values commonly use ``$=`` expressions backed by configuration
variables.  This module deliberately implements only the data-only subset the
Bridge can prove equivalent.  It never calls Python ``eval`` and it refuses
unknown variables, functions, tokens, non-finite arithmetic, and excessive
input before returning a value.
"""
from __future__ import annotations

from dataclasses import dataclass
import math
import re
from typing import Any, Mapping


MAX_EXPRESSION_CHARS = 4096
MAX_TOKENS = 512
MAX_PARSE_DEPTH = 64
MAX_EVALUATION_STEPS = 2048


class BeamNGExpressionUnsupported(ValueError):
    """The expression is outside the explicitly supported portable subset."""


@dataclass(frozen=True)
class ExpressionResolution:
    status: str
    value: Any
    variables: tuple[str, ...]
    reason: str | None = None


@dataclass(frozen=True)
class _Token:
    kind: str
    value: str
    offset: int


_NUMBER = re.compile(r"(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?")
_VARIABLE = re.compile(r"\$[A-Za-z_][A-Za-z0-9_]*")
_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
_TWO_CHAR_OPERATORS = {"==", "~=", "!=", "<=", ">="}
_ONE_CHAR_OPERATORS = set("()+-*/%^,<>")
_KEYWORDS = {"and", "or", "not", "nil", "true", "false"}
_ALLOWED_CALLS = {"case"}


def _tokenize(expression: str) -> list[_Token]:
    if not isinstance(expression, str) or not expression.startswith("$="):
        raise BeamNGExpressionUnsupported("value is not a BeamNG $= expression")
    source = expression[2:]
    if not source.strip():
        raise BeamNGExpressionUnsupported("expression is empty")
    if len(source) > MAX_EXPRESSION_CHARS:
        raise BeamNGExpressionUnsupported(
            f"expression exceeds {MAX_EXPRESSION_CHARS} characters")
    tokens: list[_Token] = []
    offset = 0
    while offset < len(source):
        if source[offset].isspace():
            offset += 1
            continue
        match = _NUMBER.match(source, offset)
        if match:
            tokens.append(_Token("number", match.group(0), offset))
            offset = match.end()
        else:
            match = _VARIABLE.match(source, offset)
            if match:
                tokens.append(_Token("variable", match.group(0), offset))
                offset = match.end()
            else:
                match = _IDENTIFIER.match(source, offset)
                if match:
                    value = match.group(0)
                    tokens.append(_Token("keyword" if value in _KEYWORDS else "identifier",
                                         value, offset))
                    offset = match.end()
                else:
                    pair = source[offset:offset + 2]
                    if pair in _TWO_CHAR_OPERATORS:
                        tokens.append(_Token("operator", pair, offset))
                        offset += 2
                    elif source[offset] in _ONE_CHAR_OPERATORS:
                        tokens.append(_Token("operator", source[offset], offset))
                        offset += 1
                    else:
                        raise BeamNGExpressionUnsupported(
                            f"unsupported token at offset {offset}: {source[offset:offset + 12]!r}")
        if len(tokens) > MAX_TOKENS:
            raise BeamNGExpressionUnsupported(f"expression exceeds {MAX_TOKENS} tokens")
    tokens.append(_Token("eof", "", len(source)))
    return tokens


class _Parser:
    def __init__(self, tokens: list[_Token]):
        self.tokens = tokens
        self.index = 0
        self.depth = 0

    @property
    def current(self) -> _Token:
        return self.tokens[self.index]

    def accept(self, value: str) -> bool:
        if self.current.value == value:
            self.index += 1
            return True
        return False

    def expect(self, value: str) -> None:
        if not self.accept(value):
            raise BeamNGExpressionUnsupported(
                f"expected {value!r} at offset {self.current.offset}")

    def parse(self) -> tuple[Any, ...]:
        node = self.parse_or()
        if self.current.kind != "eof":
            raise BeamNGExpressionUnsupported(
                f"unexpected token {self.current.value!r} at offset {self.current.offset}")
        return node

    def descend(self) -> None:
        self.depth += 1
        if self.depth > MAX_PARSE_DEPTH:
            raise BeamNGExpressionUnsupported(
                f"expression exceeds parse depth {MAX_PARSE_DEPTH}")

    def ascend(self) -> None:
        self.depth -= 1

    def parse_or(self) -> tuple[Any, ...]:
        node = self.parse_and()
        while self.accept("or"):
            node = ("binary", "or", node, self.parse_and())
        return node

    def parse_and(self) -> tuple[Any, ...]:
        node = self.parse_compare()
        while self.accept("and"):
            node = ("binary", "and", node, self.parse_compare())
        return node

    def parse_compare(self) -> tuple[Any, ...]:
        node = self.parse_add()
        if self.current.value in ("==", "~=", "!=", "<", "<=", ">", ">="):
            operator = self.current.value
            self.index += 1
            node = ("binary", operator, node, self.parse_add())
            if self.current.value in ("==", "~=", "!=", "<", "<=", ">", ">="):
                raise BeamNGExpressionUnsupported("chained comparisons are not supported")
        return node

    def parse_add(self) -> tuple[Any, ...]:
        node = self.parse_multiply()
        while self.current.value in ("+", "-"):
            operator = self.current.value
            self.index += 1
            node = ("binary", operator, node, self.parse_multiply())
        return node

    def parse_multiply(self) -> tuple[Any, ...]:
        node = self.parse_unary()
        while self.current.value in ("*", "/", "%"):
            operator = self.current.value
            self.index += 1
            node = ("binary", operator, node, self.parse_unary())
        return node

    def parse_power(self) -> tuple[Any, ...]:
        node = self.parse_primary()
        if self.accept("^"):
            node = ("binary", "^", node, self.parse_unary())
        return node

    def parse_unary(self) -> tuple[Any, ...]:
        if self.current.value in ("+", "-", "not"):
            operator = self.current.value
            self.index += 1
            return ("unary", operator, self.parse_unary())
        return self.parse_power()

    def parse_primary(self) -> tuple[Any, ...]:
        token = self.current
        if token.kind == "number":
            self.index += 1
            value = float(token.value)
            if not math.isfinite(value):
                raise BeamNGExpressionUnsupported("numeric literal is not finite")
            return ("literal", value)
        if token.kind == "variable":
            self.index += 1
            return ("variable", token.value)
        if token.kind == "keyword" and token.value in ("nil", "true", "false"):
            self.index += 1
            return ("literal", {"nil": None, "true": True, "false": False}[token.value])
        if token.kind == "identifier":
            self.index += 1
            name = token.value
            if not self.accept("("):
                raise BeamNGExpressionUnsupported(f"unknown symbol {name!r}")
            if name not in _ALLOWED_CALLS:
                raise BeamNGExpressionUnsupported(f"unsupported call {name!r}")
            self.descend()
            try:
                arguments = [self.parse_or()]
                while self.accept(","):
                    arguments.append(self.parse_or())
                self.expect(")")
            finally:
                self.ascend()
            if name == "case" and len(arguments) != 3:
                raise BeamNGExpressionUnsupported("case() requires exactly three arguments")
            return ("call", name, tuple(arguments))
        if self.accept("("):
            self.descend()
            try:
                node = self.parse_or()
                self.expect(")")
            finally:
                self.ascend()
            return node
        raise BeamNGExpressionUnsupported(
            f"expected a value at offset {token.offset}, found {token.value!r}")


def _variables(node: tuple[Any, ...], output: set[str]) -> None:
    if node[0] == "variable":
        output.add(node[1])
    elif node[0] == "unary":
        _variables(node[2], output)
    elif node[0] == "binary":
        _variables(node[2], output)
        _variables(node[3], output)
    elif node[0] == "call":
        for argument in node[2]:
            _variables(argument, output)


def _truthy(value: Any) -> bool:
    return value is not None and value is not False


class _Evaluator:
    def __init__(self, variables: Mapping[str, Any]):
        self.variables = variables
        self.steps = 0

    def evaluate(self, node: tuple[Any, ...]) -> Any:
        self.steps += 1
        if self.steps > MAX_EVALUATION_STEPS:
            raise BeamNGExpressionUnsupported(
                f"expression exceeds {MAX_EVALUATION_STEPS} evaluation steps")
        kind = node[0]
        if kind == "literal":
            return node[1]
        if kind == "variable":
            return self.variables[node[1]]
        if kind == "unary":
            operator, value = node[1], self.evaluate(node[2])
            if operator == "not":
                return not _truthy(value)
            number = self.number(value, operator)
            return number if operator == "+" else -number
        if kind == "call":
            condition = self.evaluate(node[2][0])
            return self.evaluate(node[2][1] if _truthy(condition) else node[2][2])
        operator = node[1]
        left = self.evaluate(node[2])
        if operator == "and":
            return self.evaluate(node[3]) if _truthy(left) else left
        if operator == "or":
            return left if _truthy(left) else self.evaluate(node[3])
        right = self.evaluate(node[3])
        if operator in ("==", "~=", "!="):
            equal = left == right
            return equal if operator == "==" else not equal
        if operator in ("<", "<=", ">", ">="):
            first, second = self.number(left, operator), self.number(right, operator)
            return {"<": first < second, "<=": first <= second,
                    ">": first > second, ">=": first >= second}[operator]
        first, second = self.number(left, operator), self.number(right, operator)
        try:
            if operator == "+":
                result = first + second
            elif operator == "-":
                result = first - second
            elif operator == "*":
                result = first * second
            elif operator == "/":
                if second == 0:
                    raise BeamNGExpressionUnsupported("division by zero")
                result = first / second
            elif operator == "%":
                if second == 0:
                    raise BeamNGExpressionUnsupported("modulo by zero")
                result = first % second
            elif operator == "^":
                if abs(second) > 1000:
                    raise BeamNGExpressionUnsupported("exponent exceeds the portable bound")
                # Keep the evaluator in the real-number domain. Python's
                # ``**`` can yield complex values for fractional powers of a
                # negative base, which are not portable BeamNG numerics.
                result = math.pow(first, second)
            else:  # parser admits no other binary operator
                raise BeamNGExpressionUnsupported(f"unsupported operator {operator!r}")
        except (OverflowError, ValueError, ZeroDivisionError, TypeError) as error:
            raise BeamNGExpressionUnsupported(f"invalid arithmetic: {error}") from error
        if not math.isfinite(result):
            raise BeamNGExpressionUnsupported("arithmetic result is not finite")
        return result

    @staticmethod
    def number(value: Any, operator: str) -> float:
        if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
            raise BeamNGExpressionUnsupported(
                f"operator {operator!r} requires finite numeric operands")
        return float(value)


def resolve_beamng_expression(expression: Any,
                              selected_variables: Mapping[str, Any]) -> ExpressionResolution:
    """Resolve one literal/expression without executing source code.

    Numeric literals are returned as ``literal``. Direct ``$variable``
    references and ``$=`` expressions become ``derived`` only when every
    referenced variable is present in the supplied selected configuration
    environment and evaluation stays inside the allowlist. All other values
    return ``unsupported`` with a stable reason.
    """
    if isinstance(expression, (int, float)) and not isinstance(expression, bool):
        if math.isfinite(expression):
            return ExpressionResolution("literal", float(expression), ())
        return ExpressionResolution("unsupported", None, (), "numeric literal is not finite")
    # BeamNG also permits a value to be a direct selected-variable reference,
    # without the ``$=`` expression marker. Route it through the exact same
    # parser/evaluator boundary so missing, non-scalar, and non-finite values
    # fail closed instead of falling back to a JBeam default.
    if isinstance(expression, str) and _VARIABLE.fullmatch(expression):
        expression = f"$={expression}"
    used: set[str] = set()
    try:
        tokens = _tokenize(expression)
        tree = _Parser(tokens).parse()
        _variables(tree, used)
        unknown = sorted(name for name in used if name not in selected_variables)
        if unknown:
            raise BeamNGExpressionUnsupported(
                f"unknown selected variable(s): {', '.join(unknown)}")
        non_scalar = sorted(name for name in used
                            if selected_variables[name] is not None
                            and not isinstance(selected_variables[name], (int, float, bool)))
        if non_scalar:
            raise BeamNGExpressionUnsupported(
                f"non-scalar selected variable(s): {', '.join(non_scalar)}")
        non_finite = sorted(name for name in used
                            if isinstance(selected_variables[name], float)
                            and not math.isfinite(selected_variables[name]))
        if non_finite:
            raise BeamNGExpressionUnsupported(
                f"non-finite selected variable(s): {', '.join(non_finite)}")
        value = _Evaluator(selected_variables).evaluate(tree)
        if isinstance(value, (int, float)) and not isinstance(value, bool):
            value = float(value)
            if not math.isfinite(value):
                raise BeamNGExpressionUnsupported("expression result is not finite")
        return ExpressionResolution("derived", value, tuple(sorted(used)))
    except BeamNGExpressionUnsupported as error:
        return ExpressionResolution("unsupported", None, tuple(sorted(used)), str(error))
