from dataclasses import dataclass
from typing import Optional, Union
import networkx as nx

@dataclass
class ASTNode:
value: str
left: Optional['ASTNode'] = None
right: Optional['ASTNode'] = None

def evaluate(self) -> Union[int, float]: """Recursively evaluates the AST node.""" # If it's a leaf node (number), return its numeric value if self.left is None and self.right is None: return float(self.value) if "." in self.value else int(self.value) left_val = self.left.evaluate() if self.left else 0 right_val = self.right.evaluate() if self.right else 0 # Apply operator op = self.value if op in ("+", "circled_plus"): return left_val + right_val elif op in ("-", "minus"): return left_val - right_val elif op in ("*", "times", "x"): return left_val * right_val elif op in ("/", "divide"): return left_val / right_val if right_val != 0 else float('inf') else: raise ValueError(f"Unsupported operator in AST: {op}") 

def build_ast_from_document(doc: SymbolicDocument) -> Optional[ASTNode]:
"""
Constructs an Abstract Syntax Tree from a SymbolicDocument
by following topological order or spatial/relational edges.
"""
# 1. Convert to NetworkX graph
G = nx.DiGraph()
for sym in doc.symbols:
G.add_node(sym.symbol_id, **asdict(sym))
for rel in doc.relations:
G.add_edge(rel.source_id, rel.target_id, **asdict(rel))

if G.number_of_nodes() == 0: return None # 2. Find nodes (numbers vs operators) # For a simple linear expression like [n1] -> [op] -> [n2], # let's find an operator node to act as the root. operator_nodes = [n for n, d in G.nodes(data=True) if d.get("kind") == "operator"] number_nodes = [n for n, d in G.nodes(data=True) if d.get("kind") == "number"] if operator_nodes: # Pick the first operator as root (or traverse based on precedence) root_id = operator_nodes[0] root_data = G.nodes[root_id] root_val = root_data.get("raw_text") or root_data.get("symbol_id") # Find predecessors (left child) and successors (right child) in the graph preds = list(G.predecessors(root_id)) succs = list(G.successors(root_id)) left_child = None right_child = None if preds: p_data = G.nodes[preds[0]] left_child = ASTNode(value=str(p_data.get("raw_text", p_data.get("value")))) if succs: s_data = G.nodes[succs[0]] right_child = ASTNode(value=str(s_data.get("raw_text", s_data.get("value")))) return ASTNode(value=root_val, left=left_child, right=right_child) elif len(number_nodes) == 1: # Single number fallback n_data = G.nodes[number_nodes[0]] return ASTNode(value=str(n_data.get("raw_text", n_data.get("value")))) return None