import json
import uuid

file_path = 'workflows/Binance Altcoin Price Logger.json'
with open(file_path, 'r', encoding='utf-8') as f:
    data = json.load(f)

nodes = data['nodes']
connections = data['connections']

# Nodes that need guards
critical_nodes = [
    'Sync State',
    'Fetch All Tickers',
    'Fetch BTC Klines',
    'Fetch Klines for Winner',
    'Fetch Real Balance',
    'Fetch Exchange Info'
]

for node_name in critical_nodes:
    # Find the node
    node = next((n for n in nodes if n['name'] == node_name), None)
    if not node:
        continue

    # Create a guard node (If node)
    guard_name = f"Guard {node_name}"
    guard_node = {
        "parameters": {
            "conditions": {
                "options": {
                    "caseSensitive": True,
                    "leftValue": "={{ $json.error || !($json.balances || $json.balances && $json.balances.length > 0 || Array.isArray($json) || typeof $json === 'object') }}",
                    "operator": "isEmpty",
                    "rightValue": ""
                }
            }
        },
        "id": str(uuid.uuid4()),
        "name": guard_name,
        "type": "n8n-nodes-base.if",
        "typeVersion": 1,
        "position": [node['position'][0] + 200, node['position'][1]]
    }
    nodes.append(guard_node)

    # Update connections
    # 1. Find who points to the critical node
    for source_node, outputs in connections.items():
        for output_list in outputs.get('main', []):
            for target in output_list:
                if target['node'] == node_name:
                    target['node'] = guard_name

    # 2. Point critical node to guard
    connections[node_name] = {
        "main": [[{"node": guard_name, "type": "main", "index": 0}]]
    }

    # 3. Point guard (true path) to original target of critical node
    # Find original target of critical node
    original_targets = connections.get(node_name, {}).get('main', [])
    # Actually, we just set connections[node_name] above, so we need to know where it WAS going.
    # Let's re-read the original connections map before we modified it.
    # Wait, I should have saved the original connections.

with open(file_path, 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2)
