#!/usr/bin/env python3
"""
Fetch the live n8n onboarding workflow, add:
  1. Services Enabled column in the queue append
  2. Dedupe Check node (Google Sheets lookup by GHL Contact ID)
  3. Is Duplicate? IF node
  4. Respond - Duplicate node
Rewire connections. PUT back.
"""
import os, sys, json, urllib.request, urllib.parse

BASE = os.environ["N8N_BASE_URL"].rstrip("/")
KEY  = os.environ["N8N_API_KEY"]
WF_ID = "21cXlP5tZ1WF3PIq"

QUEUE_SHEET_ID = "1FX0eDt9d322XYcOQRp8b9tXkRrrrHcSWJ9maXEwYk7k"
GS_CREDS = {"googleSheetsOAuth2Api": {"id": "OhjizsinSISmx4Gl", "name": "Google Sheets OAuth2 API"}}

def api(method, path, body=None):
    req = urllib.request.Request(
        f"{BASE}{path}",
        method=method,
        headers={
            "X-N8N-API-KEY": KEY,
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        data=json.dumps(body).encode() if body is not None else None,
    )
    try:
        resp = urllib.request.urlopen(req, timeout=30)
        return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        print(f"HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
        raise

# 1. Fetch current workflow
wf = api("GET", f"/api/v1/workflows/{WF_ID}")
print(f"Fetched: {wf['name']} ({len(wf['nodes'])} nodes)")

# 2. Update queue append node to include Services Enabled
for n in wf["nodes"]:
    if n["name"] == "Sheets — Add to Onboarding Queue":
        cols = n["parameters"].get("columns", {}).get("value", {})
        cols["Services Enabled"] = "={{ $('Onboarding Webhook').item.json.body.services_enabled || 'dashboard,resources' }}"
        # Also update the schema so n8n knows about the new column (typeVersion 4+)
        schema = n["parameters"].get("columns", {}).get("schema", [])
        existing_names = {s.get("id") or s.get("displayName") for s in schema}
        if "Services Enabled" not in existing_names and schema:
            schema.append({
                "id": "Services Enabled",
                "displayName": "Services Enabled",
                "required": False,
                "defaultMatch": False,
                "display": True,
                "type": "string",
                "canBeUsedToMatch": True,
            })
        print("  ✓ Added Services Enabled to queue append")

# 3. Check if dedupe nodes already exist — skip if so
existing_names = {n["name"] for n in wf["nodes"]}
if "Check Queue for Duplicate" not in existing_names:
    # Insert new nodes
    dedupe_node = {
        "parameters": {
            "operation": "lookup",
            "documentId": {"__rl": True, "value": QUEUE_SHEET_ID, "mode": "id"},
            "sheetName": {"__rl": True, "value": "gid=0", "mode": "id"},
            "filtersUI": {
                "values": [
                    {
                        "lookupColumn": "GHL Contact ID",
                        "lookupValue": "={{ $('GHL — Upsert Contact').item.json.contact.id }}",
                    }
                ]
            },
            "combineFilters": "AND",
            "options": {"returnFirstMatch": True},
        },
        "id": "dedupe01-0001-0001-0001-dedupe01aaaa",
        "name": "Check Queue for Duplicate",
        "type": "n8n-nodes-base.googleSheets",
        "typeVersion": 4.5,
        "position": [880, 60],
        "credentials": GS_CREDS,
        "alwaysOutputData": True,
    }

    is_duplicate_node = {
        "parameters": {
            "conditions": {
                "options": {"caseSensitive": True, "leftValue": "", "typeValidation": "loose"},
                "conditions": [
                    {
                        "id": "dup-check-id",
                        "leftValue": "={{ $json['GHL Contact ID'] }}",
                        "rightValue": "",
                        "operator": {"type": "string", "operation": "notEmpty", "singleValue": True},
                    }
                ],
                "combinator": "and",
            },
            "options": {},
        },
        "id": "dedupe02-0002-0002-0002-dedupe02bbbb",
        "name": "Is Duplicate?",
        "type": "n8n-nodes-base.if",
        "typeVersion": 2.2,
        "position": [1100, 60],
    }

    respond_duplicate_node = {
        "parameters": {
            "respondWith": "json",
            "responseBody": "={{ JSON.stringify({ ok: true, duplicate: true, message: 'Already in onboarding queue', contactId: $('GHL — Upsert Contact').item.json.contact.id }) }}",
            "options": {},
        },
        "id": "dedupe03-0003-0003-0003-dedupe03cccc",
        "name": "Respond - Already Queued",
        "type": "n8n-nodes-base.respondToWebhook",
        "typeVersion": 1.1,
        "position": [1320, 60],
    }

    wf["nodes"].extend([dedupe_node, is_duplicate_node, respond_duplicate_node])
    print("  ✓ Added dedupe nodes")

    # 4. Rewire connections
    conns = wf["connections"]

    # GHL Create Note currently → [Sheets Add Queue, Gmail Notify]
    # Change to: GHL Create Note → Check Queue for Duplicate
    conns["GHL — Create Note"] = {
        "main": [[{"node": "Check Queue for Duplicate", "type": "main", "index": 0}]]
    }

    # Check Queue for Duplicate → Is Duplicate?
    conns["Check Queue for Duplicate"] = {
        "main": [[{"node": "Is Duplicate?", "type": "main", "index": 0}]]
    }

    # Is Duplicate? true (index 0) → Respond - Already Queued
    # Is Duplicate? false (index 1) → [Sheets Add Queue, Gmail Notify]
    conns["Is Duplicate?"] = {
        "main": [
            [{"node": "Respond - Already Queued", "type": "main", "index": 0}],  # true branch
            [  # false branch
                {"node": "Sheets — Add to Onboarding Queue", "type": "main", "index": 0},
                {"node": "Gmail — Notify Bryce", "type": "main", "index": 0},
            ],
        ]
    }
    print("  ✓ Rewired connections")
else:
    print("  (dedupe nodes already present, skipping insert)")

# 5. PUT back. n8n API PUT only accepts certain fields — strip read-only ones.
update_body = {
    "name": wf["name"],
    "nodes": wf["nodes"],
    "connections": wf["connections"],
    "settings": wf.get("settings", {}),
    "staticData": wf.get("staticData"),
}

try:
    result = api("PUT", f"/api/v1/workflows/{WF_ID}", update_body)
    print(f"✓ Updated workflow successfully. Active: {result.get('active')}")
except Exception as e:
    print(f"✗ PUT failed: {e}")
    sys.exit(1)
