#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os

# Agregar el directorio padre al path
sys.path.append('.')

# Importar el convertidor
from x1_lad_converter import SimpleLadConverter

def test_filling_head_pid():
    """Probar específicamente _FILLING_HEAD_PID_CTRL.EXP con parser mejorado"""
    print("=== TEST: _FILLING_HEAD_PID_CTRL.EXP con parser mejorado ===")
    print("Verificando detección de patrones ??? para ACTION calls")
    print("-" * 60)
    
    # Buscar el archivo
    possible_paths = [
        "ExportTwinCat/_FILLING_HEAD_PID_CTRL.EXP",
        "../ExportTwinCat/_FILLING_HEAD_PID_CTRL.EXP",
        "../../ExportTwinCat/_FILLING_HEAD_PID_CTRL.EXP",
        "C:/Trabajo/SIDEL/13 - E5.007560 - Modifica O&U - SAE235/Reporte/ExportTwinCat/_FILLING_HEAD_PID_CTRL.EXP"
    ]
    
    test_file = None
    for path in possible_paths:
        if os.path.exists(path):
            test_file = path
            break
    
    if test_file is None:
        print(f"❌ Error: No se encontró _FILLING_HEAD_PID_CTRL.EXP")
        return
    
    print(f"✓ Archivo encontrado: {test_file}")
    print("-" * 60)
    
    # Crear convertidor
    converter = SimpleLadConverter()
    
    # Parsear archivo
    print("🔍 PARSEANDO ARCHIVO CON PARSER MEJORADO...")
    converter.parse_file(test_file)
    
    print(f"\n📊 RESUMEN:")
    print(f"  ✓ Programa: {converter.program_name}")
    print(f"  ✓ Redes encontradas: {len(converter.networks)}")
    print(f"  ✓ ACTIONs encontradas: {list(converter.actions.keys())}")
    
    # Analizar tipos de llamadas encontradas
    action_calls = []
    function_blocks = []
    unresolved_calls = []
    
    print(f"\n🔍 ANÁLISIS DE REDES:")
    for i, network in enumerate(converter.networks):
        if network['logic']:
            logic_type = network['logic']['type']
            logic_name = network['logic'].get('name', 'Sin nombre')
            
            if logic_type == 'ACTION_CALL':
                action_calls.append(logic_name)
                if logic_name == '???':
                    unresolved_calls.append(f"Red {network['id']}")
                    print(f"  ❌ Red {network['id']}: ACTION call SIN RESOLVER → {logic_name}")
                else:
                    print(f"  ✅ Red {network['id']}: ACTION call RESUELTO → {logic_name}")
            elif logic_type == 'FUNCTION_BLOCK':
                function_blocks.append(logic_name)
                print(f"  🔧 Red {network['id']}: Function Block → {logic_name}")
            else:
                print(f"  ℹ Red {network['id']}: {logic_type} → {logic_name}")
    
    print(f"\n📈 ESTADÍSTICAS:")
    print(f"  📞 ACTION calls encontradas: {len(action_calls)}")
    print(f"     ✅ Resueltas: {len([x for x in action_calls if x != '???'])}")
    print(f"     ❌ Sin resolver: {len([x for x in action_calls if x == '???'])}")
    print(f"  🔧 Function Blocks: {len(function_blocks)}")
    
    if unresolved_calls:
        print(f"\n⚠ REDES CON PROBLEMAS:")
        for call in unresolved_calls:
            print(f"     • {call}")
    
    # Generar código SCL para verificar
    print(f"\n📝 GENERANDO CÓDIGO SCL...")
    scl_code = converter.convert_to_structured()
    
    # Guardar archivo de prueba
    output_file = "test_filling_head_debug.scl"
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(scl_code)
    
    print(f"  ✓ Guardado en: {output_file}")
    
    # Buscar problemas en el código generado
    lines = scl_code.split('\n')
    problem_lines = []
    for i, line in enumerate(lines, 1):
        if '???' in line:
            problem_lines.append(f"Línea {i}: {line.strip()}")
    
    if problem_lines:
        print(f"\n⚠ PROBLEMAS EN CÓDIGO SCL GENERADO:")
        for problem in problem_lines:
            print(f"     • {problem}")
    else:
        print(f"\n✅ CÓDIGO SCL SIN PROBLEMAS ??? DETECTADOS")
    
    # Mostrar sección principal del código generado
    print(f"\n📄 CÓDIGO PRINCIPAL (primeras 30 líneas relevantes):")
    main_start = -1
    for i, line in enumerate(lines):
        if "CÓDIGO PRINCIPAL" in line:
            main_start = i
            break
    
    if main_start > -1:
        relevant_lines = []
        for i in range(main_start, min(main_start + 50, len(lines))):
            line = lines[i]
            if ('CALL ' in line or 
                'Red ' in line or 
                'IF ' in line or
                'mDummy :=' in line):
                relevant_lines.append(f"  {i+1:3d}: {line}")
        
        for line in relevant_lines[:30]:
            print(line)
        
        if len(relevant_lines) > 30:
            print(f"    ... ({len(relevant_lines) - 30} líneas más)")
    
    return scl_code

if __name__ == "__main__":
    test_filling_head_pid() 