#!/usr/bin/env python3
"""Trace parsing decisions"""

from src.alloy.parser import AlloyParser
from src.alloy.lexer import AlloyLexer

# Override the parser error function to get more info
class DebugParser(AlloyParser):
    def p_error(self, p):
        """Handle syntax errors with more detail"""
        if p:
            print(f"ERROR: Syntax error at token '{p.value}' (type: {p.type}, line {p.lineno})")
            # Show the parser state
            print(f"Parser stack: {[str(s) for s in self.parser.symstack]}")
        else:
            print("ERROR: Syntax error at EOF")
            print(f"Parser stack: {[str(s) for s in self.parser.symstack if s]}")

# Test
lexer = AlloyLexer()
parser = DebugParser(lexer)

code = 'review = alloy Review code'
print(f"Parsing: {code}")
print("-" * 50)

# Parse with very verbose debug
import sys
old_stdout = sys.stdout
class DebugOutput:
    def __init__(self):
        self.data = []
    def write(self, s):
        self.data.append(s)
        if 'ERROR' in s or 'error' in s:
            old_stdout.write(s)
    def flush(self):
        pass

debug_out = DebugOutput()
sys.stdout = debug_out

try:
    result = parser.parse(code, debug=True)
finally:
    sys.stdout = old_stdout

# Find the key decision points
print("\nKey parsing decisions:")
for line in debug_out.data:
    if 'alloy' in line.lower() or 'reduce' in line.lower() or 'shift' in line.lower():
        print(line.strip())