#!/usr/bin/env python3
import os, requests, json
from pathlib import Path

env = Path('.env').read_text()
for line in env.splitlines():
    line = line.strip()
    if line and not line.startswith('#') and '=' in line:
        k, _, v = line.partition('=')
        os.environ.setdefault(k.strip(), v.strip())

BASE = os.environ['N8N_BASE_URL'].rstrip('/')
KEY = os.environ['N8N_API_KEY']
headers = {'X-N8N-API-KEY': KEY, 'Content-Type': 'application/json'}

NEW_CODE = """// Personalize the HTML template for each email
const prevData = $('Should Send?').first().json;
const fetchResult = $input.first().json;
const html = fetchResult.data || fetchResult.body || String(fetchResult);
const firstName = prevData.first_name || 'there';
const message = (prevData.message || '').trim();
const emailNumber = prevData.email_number || 1;

// Email 1 only: inject a natural reference to what they wrote in the form
let personalOpener = '';
if (emailNumber === 1 && message) {
  const trimmed = message.length > 200 ? message.substring(0, 200).trim() + '...' : message;
  personalOpener = `<p style="margin:0 0 18px 0;">I read through your note: <em>"${trimmed}"</em> That actually helps a lot.</p>`;
}

const personalizedHtml = html
  .replace(/\\{\\{First Name\\}\\}/g, firstName)
  .replace(/\\{\\{PERSONAL_OPENER\\}\\}/g, personalOpener);

return [{
  json: {
    to: prevData.to,
    subject: prevData.subject,
    html: personalizedHtml
  }
}];"""

r = requests.get(f'{BASE}/api/v1/workflows/OHmKuj5pbtywk06C', headers=headers)
wf = r.json()

for node in wf['nodes']:
    if node['name'] == 'Personalize':
        node['parameters']['jsCode'] = NEW_CODE
        print('Updated Personalize node')
        break

payload = {
    'name': wf['name'],
    'nodes': wf['nodes'],
    'connections': wf['connections'],
    'settings': wf.get('settings', {}),
    'staticData': wf.get('staticData', None),
}

r2 = requests.put(f'{BASE}/api/v1/workflows/OHmKuj5pbtywk06C', headers=headers, json=payload)
print('Status:', r2.status_code)
if not r2.ok:
    print(r2.text[:500])
else:
    print('Workflow saved successfully')
