import sys
import ast

def check_syntax(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        source = f.read()
    
    try:
        ast.parse(source)
        print(f"✓ El archivo {filename} no tiene errores de sintaxis.")
        return True
    except SyntaxError as e:
        print(f"✗ Error de sintaxis en {filename}, línea {e.lineno}, columna {e.offset}")
        print(f"  {e.text.strip()}")
        print(f"  {' ' * (e.offset - 1)}^")
        print(f"  {e}")
        
        # Mostrar contexto alrededor del error
        with open(filename, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        
        start = max(0, e.lineno - 5)
        end = min(len(lines), e.lineno + 5)
        
        print("\nContexto del error:")
        for i in range(start, end):
            prefix = "-> " if i + 1 == e.lineno else "   "
            print(f"{prefix}{i + 1}: {lines[i].rstrip()}")
        
        return False

if __name__ == "__main__":
    filename = "app/services/tariff_detector.py"
    if len(sys.argv) > 1:
        filename = sys.argv[1]
    
    check_syntax(filename)
