import json
import urllib.request
import urllib.parse

API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzNzQ0MDIxNi1lMmJhLTRlYjEtODAzMy0wMjI4ZGM0NzE1ZmUiLCJpc3MiOiJuOG4iLCJhdWQiOiJwdWJsaWMtYXBpIiwianRpIjoiZjNmMGI0OGYtYWY2OS00MjhhLWI1YzctNjA5MDYxMGQ5NGJhIiwiaWF0IjoxNzc5NzM1OTY3LCJleHAiOjE3ODc0NTc2MDB9.7Sym-gkjzlahv0Sg2wi0KGX4uo7_Y05nRARF64G5Log"
WORKFLOW_ID = "jxcLkcHkPFWcO6Wv"
URL = f"http://localhost:5678/api/v1/workflows/{WORKFLOW_ID}"

# First, get the workflow
req = urllib.request.Request(URL, headers={"X-N8N-API-KEY": API_KEY})
try:
    with urllib.request.urlopen(req) as response:
        workflow = json.loads(response.read().decode())
except Exception as e:
    print(f"Failed to fetch workflow: {e}")
    exit(1)

# Modify nodes
email_node = None
write_node = None
exec_node = None

for node in workflow['nodes']:
    if node['name'] == 'EmailReadImap':
        email_node = node
    elif node['name'] == 'Write Binary File':
        write_node = node
    elif node['name'] == 'Execute Command':
        exec_node = node

if email_node:
    email_node['position'] = [1296, 176]
    if 'options' not in email_node['parameters']:
        email_node['parameters']['options'] = {}
    email_node['parameters']['options']['customEmailConfig'] = '["FROM \\"ricardo.amorim@wkve.com.br\\""]'

if write_node:
    write_node['position'] = [1632, 176]
    write_node['parameters']['fileName'] = '=/tmp/{{$json.fileName}}'
    write_node['parameters']['dataPropertyName'] = 'data'

if exec_node:
    exec_node['position'] = [1856, 176]
    exec_node['parameters']['command'] = '=/var/www/html/robot/.venv/bin/python3 /var/www/html/robot/execution/process_attachment_sgd.py "{{$json.fileName}}"'

split_node = {
    "parameters": {
        "jsCode": "const result = [];\nfor (const item of $input.all()) {\n  if (item.binary) {\n    for (const key of Object.keys(item.binary)) {\n      result.push({\n        json: {\n          ...item.json,\n          attachmentKey: key,\n          fileName: item.binary[key].fileName\n        },\n        binary: {\n          data: item.binary[key]\n        }\n      });\n    }\n  } else {\n    result.push(item);\n  }\n}\nreturn result;"
    },
    "name": "Split Attachments",
    "type": "n8n-nodes-base.code",
    "typeVersion": 2,
    "position": [1464, 176],
    "id": "a2cf68bf-9ff9-4418-a284-639512dbd607"
}

workflow['nodes'] = [n for n in [email_node, split_node, write_node, exec_node] if n is not None]

# Modify connections
workflow['connections'] = {
    "EmailReadImap": {
        "main": [
            [
                {
                    "node": "Split Attachments",
                    "type": "main",
                    "index": 0
                }
            ]
        ]
    },
    "Split Attachments": {
        "main": [
            [
                {
                    "node": "Write Binary File",
                    "type": "main",
                    "index": 0
                }
            ]
        ]
    },
    "Write Binary File": {
        "main": [
            [
                {
                    "node": "Execute Command",
                    "type": "main",
                    "index": 0
                }
            ]
        ]
    }
}

# Update workflow
update_data = {
    "name": workflow['name'],
    "nodes": workflow['nodes'],
    "connections": workflow['connections'],
    "settings": {"executionOrder": workflow.get('settings', {}).get('executionOrder', 'v1')}
}

req_update = urllib.request.Request(URL, data=json.dumps(update_data).encode('utf-8'), headers={
    "X-N8N-API-KEY": API_KEY,
    "Content-Type": "application/json"
}, method='PUT')

try:
    with urllib.request.urlopen(req_update) as response:
        print("Workflow updated successfully")
        with open("/var/www/html/robot/workflow.json", "w") as f:
            json.dump(update_data, f, indent=2)
        print("Local workflow.json updated successfully")
except Exception as e:
    print(f"Failed to update workflow: {e}")
    if hasattr(e, 'read'):
        print("Response body:", e.read().decode())
