#!/usr/bin/env python3
"""Prepare TradiesVoice workflow JSON for n8n API import."""

import json
import re
import sys

def strip_non_ascii_name(name):
    """Keep only printable ASCII characters."""
    return re.sub(r'[^\x20-\x7E]', '', name).strip()

def main():
    with open(r"E:\genesis-system\TRADIES\onboarding\n8n_provisioning_workflow.json", "r", encoding="utf-8") as f:
        wf = json.load(f)
    
    print(f"Loaded workflow: {wf['name']}")
    print(f"Node count: {len(wf['nodes'])}")
    
    # Build name map (original -> cleaned)
    name_map = {}
    for node in wf['nodes']:
        original = node['name']
        cleaned = strip_non_ascii_name(original)
        if not cleaned:
            cleaned = f"Node-{node['id']}"
        name_map[original] = cleaned
        if original != cleaned:
            print(f"  Renamed: '{original}' -> '{cleaned}'")
    
    # Fix nodes
    clean_nodes = []
    for node in wf['nodes']:
        cn = {
            "id": node["id"],
            "name": name_map[node["name"]],
            "type": node["type"],
            "typeVersion": node["typeVersion"],
            "position": node["position"],
            "parameters": {}
        }
        
        # Handle wait node - needs 'resume' parameter
        if node["type"] == "n8n-nodes-base.wait":
            cn["parameters"] = {
                "resume": "timeInterval",
                "unit": "seconds",
                "amount": 30
            }
        elif node["type"] == "n8n-nodes-base.respondToWebhook":
            # respondToWebhook parameters  
            cn["parameters"] = {
                "respondWith": "json",
                "responseBody": '={ "status": "success", "provisioningId": "{{ $json.provisioningId }}", "message": "Client provisioned successfully" }'
            }
        else:
            # Fix URL fields - replace template placeholders with valid URLs for Slack
            params = dict(node.get("parameters", {}))
            if params.get("url") == "{{SLACK_WEBHOOK_URL}}":
                params["url"] = "https://hooks.slack.com/services/REPLACE_WITH_WEBHOOK"
            cn["parameters"] = params
        
        clean_nodes.append(cn)
    
    # Fix connections - update node names
    clean_connections = {}
    for conn_key, conn_val in wf.get("connections", {}).items():
        clean_key = name_map.get(conn_key, conn_key)
        # Also fix target node names in the connections
        # conn_val is like {"main": [[{"node": "NodeName", "type": "main", "index": 0}]]}
        clean_val = {}
        for port_type, port_arrays in conn_val.items():
            clean_port = []
            for arr in port_arrays:
                clean_arr = []
                for target in arr:
                    clean_target = dict(target)
                    if "node" in clean_target:
                        clean_target["node"] = name_map.get(clean_target["node"], clean_target["node"])
                    clean_arr.append(clean_target)
                clean_port.append(clean_arr)
            clean_val[port_type] = clean_port
        clean_connections[clean_key] = clean_val
    
    # Build final payload
    payload = {
        "name": "TradiesVoice Client Provisioning",
        "nodes": clean_nodes,
        "connections": clean_connections,
        "settings": {"executionOrder": "v1"}
    }
    
    output_path = r"E:\genesis-system\TRADIES\onboarding\n8n_workflow_clean.json"
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(payload, f, indent=2, ensure_ascii=False)
    
    print(f"\nSaved clean workflow to: {output_path}")
    print(f"Nodes: {len(clean_nodes)}")
    print(f"Connections keys: {list(clean_connections.keys())[:5]}...")
    
    # Also print node names for verification
    print("\nFinal node names:")
    for n in clean_nodes:
        print(f"  [{n['id']}] {n['name']} ({n['type']})")

if __name__ == "__main__":
    main()
