# processors/duplicate_uid_handler.py
"""
Manejador de UIDs duplicados en el JSON
"""

def detect_and_resolve_duplicate_uids(data):
    """
    Detecta y resuelve UIDs duplicados en el JSON de datos.
    Estrategia: Renombrar UIDs duplicados añadiendo sufijo _dup1, _dup2, etc.
    """
    uid_counts = {}
    modifications_made = 0
    
    print("INFO: Detectando UIDs duplicados...")
    
    # Primera pasada: contar UIDs
    for network in data.get("networks", []):
        network_id = network.get("id", "Unknown")
        for instruction in network.get("logic", []):
            uid = instruction.get("instruction_uid")
            if uid:
                if uid not in uid_counts:
                    uid_counts[uid] = []
                uid_counts[uid].append((network_id, instruction))
    
    # Segunda pasada: renombrar duplicados
    for uid, instances in uid_counts.items():
        if len(instances) > 1:
            print(f"INFO: UID duplicado encontrado: {uid} ({len(instances)} instancias)")
            
            # Mantener la primera instancia, renombrar las demás
            for i, (network_id, instruction) in enumerate(instances[1:], 1):
                old_uid = instruction["instruction_uid"]
                new_uid = f"{old_uid}_dup{i}"
                instruction["instruction_uid"] = new_uid
                modifications_made += 1
                
                print(f"  - Red {network_id}: UID {old_uid} → {new_uid}")
                
                # También actualizar referencias en otras instrucciones
                update_uid_references(data, old_uid, new_uid, network_id)
    
    if modifications_made > 0:
        print(f"INFO: Se resolvieron {modifications_made} UIDs duplicados")
    else:
        print("INFO: No se encontraron UIDs duplicados")
    
    return modifications_made > 0

def update_uid_references(data, old_uid, new_uid, target_network_id):
    """
    Actualiza las referencias al UID antiguo en conexiones de otras instrucciones
    dentro de la misma red.
    """
    for network in data.get("networks", []):
        if network.get("id") != target_network_id:
            continue
            
        for instruction in network.get("logic", []):
            # Buscar en inputs que tengan source_instruction_uid
            for pin_name, pin_info in instruction.get("inputs", {}).items():
                if isinstance(pin_info, dict):
                    if pin_info.get("source_instruction_uid") == old_uid:
                        pin_info["source_instruction_uid"] = new_uid
                        print(f"    - Actualizada referencia en instrucción {instruction.get('instruction_uid')} pin {pin_name}")
