File size: 20,500 Bytes
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e6fbaf
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e6fbaf
2dfd598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import dns from 'dns';

dns.setDefaultResultOrder('ipv4first');

// Load environment variables from .env or .env.local
dotenv.config({ path: '.env.local' });
dotenv.config();

const app = express();
const PORT = process.env.PORT || 7860;
const FORMBRICKS_BASE_URL = process.env.FORMBRICKS_URL || 'https://app.formbricks.com';

app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));

// -------------------------------------------------------------
// Live API Service Calls (Node Native Fetch)
// -------------------------------------------------------------

async function translateDeepL(texts, targetLang, apiKey) {
  if (!apiKey) throw new Error("DeepL API açarı daxil edilməyib.");
  
  // Normalize DeepL target language codes (BR -> PT-BR for Brazilian Portuguese, not Breton)
  let deeplTarget = (targetLang || '').toUpperCase();
  if (deeplTarget === 'BR') deeplTarget = 'PT-BR';
  if (deeplTarget === 'PT') deeplTarget = 'PT-PT';

  const isFreeKey = apiKey.endsWith(':fx');
  const url = isFreeKey 
    ? 'https://api-free.deepl.com/v2/translate' 
    : 'https://api.deepl.com/v2/translate';
    
  const response = await fetchWithRetry(url, {
    method: 'POST',
    headers: {
      'Authorization': `DeepL-Auth-Key ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      text: texts,
      target_lang: deeplTarget,
      tag_handling: 'html'
    })
  });
  
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`DeepL API Xətası: ${response.status} - ${errorText}`);
  }
  const data = await response.json();
  return data.translations.map(t => t.text);
}

// Helper for retrying requests on Rate Limits (429), Overloads (529), or Service Unavailable (503)
async function fetchWithRetry(url, options, maxRetries = 4, initialDelay = 1500) {
  let delay = initialDelay;
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      if ([429, 529, 503].includes(response.status) && attempt < maxRetries) {
        console.warn(`API overloaded/rate-limited (${response.status}). Cəhd ${attempt}/${maxRetries}. ${Math.round(delay/1000)}s sonra təkrar cəhd edilir...`);
        await new Promise(res => setTimeout(res, delay));
        delay = Math.min(delay * 1.5, 3500);
        continue;
      }
      return response;
    } catch (err) {
      if (attempt < maxRetries) {
        await new Promise(res => setTimeout(res, delay));
        delay = Math.min(delay * 1.5, 3500);
        continue;
      }
      throw err;
    }
  }
}

async function reviewGemini(original, translation, targetLangName, apiKey, fullContext, contentType = "General JSON Content") {
  if (!apiKey) throw new Error("Gemini API açarı daxil edilməyib.");
  const apiModel = process.env.VITE_GEMINI_MODEL || 'gemini-3.5-flash';
  const url = `https://generativelanguage.googleapis.com/v1beta/models/${apiModel}:generateContent?key=${apiKey}`;
  const prompt = `You are a native speaker of ${targetLangName}. Review this ${contentType} segment translation.

=== FULL CONTENT CONTEXT (For your understanding) ===
${fullContext || "N/A"}
=== END FULL CONTEXT ===

TARGET SEGMENT TO REVIEW:
Original English: "${original}"
DeepL Translation: "${translation}"

Review the translation for natural flow, domain accuracy (${contentType}), correct variables (like {{$username}}, {{name}}, {count}), and native style.
If the translation is already perfect and natural, reply with exactly: "APPROVED".
Otherwise, reply with your improved translation and a 1-sentence explanation of the correction. Keep HTML tags intact.`;

  const response = await fetchWithRetry(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      contents: [{ parts: [{ text: prompt }] }]
    })
  });
  
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Gemini API Xətası: ${response.status} - ${errorText}`);
  }
  const data = await response.json();
  return data.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || "Rəy əldə edilə bilmədi.";
}

async function reviewOpenAI(original, translation, targetLangName, apiKey, fullContext, contentType = "General JSON Content") {
  if (!apiKey) throw new Error("OpenAI API açarı daxil edilməyib.");
  const response = await fetchWithRetry('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      model: process.env.VITE_OPENAI_MODEL || 'gpt-4o',
      messages: [
        { role: 'system', content: `You are an expert native reviewer and localizer for ${targetLangName} specializing in ${contentType}.` },
        { role: 'user', content: `Review this translated segment:

=== FULL CONTENT CONTEXT (For reference) ===
${fullContext || "N/A"}
=== END CONTEXT ===

TARGET SEGMENT:
Original: "${original}"
DeepL Translation: "${translation}"

Verify if it sounds natural, local, and maintains correct HTML formatting and template variables.
If it is perfect, output "APPROVED".
Otherwise, provide your improved translation and 1 brief suggestion.` }
      ],
      temperature: 0.3
    })
  });
  
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`OpenAI API Xətası: ${response.status} - ${errorText}`);
  }
  const data = await response.json();
  return data.choices?.[0]?.message?.content?.trim() || "Rəy əldə edilə bilmədi.";
}

function safeParseJson(rawText) {
  if (!rawText) return null;
  let cleaned = rawText.replace(/^```json\s*/i, '').replace(/```$/g, '').trim();

  // Try direct parse first
  try {
    return JSON.parse(cleaned);
  } catch (e0) {}

  const jsonStart = cleaned.indexOf('{');
  if (jsonStart === -1) return null;

  let jsonEnd = cleaned.lastIndexOf('}');
  if (jsonEnd === -1 || jsonEnd <= jsonStart) {
    // If closing } is missing (truncated output), auto-close quotes/curly braces
    cleaned = cleaned + '"}';
    jsonEnd = cleaned.lastIndexOf('}');
  }

  let jsonStr = cleaned.substring(jsonStart, jsonEnd + 1);

  // 1. Try standard JSON parse
  try {
    return JSON.parse(jsonStr);
  } catch (e1) {
    // 2. Try fixing raw control characters/newlines inside string literals
    try {
      const fixedStr = jsonStr.replace(/[\r\n]+/g, " ");
      return JSON.parse(fixedStr);
    } catch (e2) {
      // 3. Robust Regex Extraction Fallback for fields (even if output was truncated!)
      const finalTransMatch = jsonStr.match(/"final_translation"\s*:\s*"([\s\S]*?)"\s*,\s*"agent_notes"/i) 
        || jsonStr.match(/"final_translation"\s*:\s*"([\s\S]*?)"\s*[\},]/i)
        || jsonStr.match(/"final_translation"\s*:\s*"([\s\S]*)/i);

      const agentNotesMatch = jsonStr.match(/"agent_notes"\s*:\s*"([\s\S]*?)"\s*[\},]/i);
      const conflictMatch = jsonStr.match(/"discrepancy_percentage"\s*:\s*(\d+)/i);

      if (finalTransMatch && finalTransMatch[1]) {
        let cleanTrans = finalTransMatch[1]
          .replace(/\\"/g, '"')
          .replace(/"\s*,\s*"agent_notes"[\s\S]*/i, '')
          .replace(/"\s*\}$/, '')
          .trim();

        return {
          final_translation: cleanTrans,
          agent_notes: agentNotesMatch ? agentNotesMatch[1] : "Claude tərəfindən sintez edildi.",
          discrepancy_percentage: conflictMatch ? parseInt(conflictMatch[1]) : 0
        };
      }
    }
  }
  return null;
}

async function synthesizeClaude(original, deeplText, geminiReview, openaiReview, targetLangName, apiKey, fullContext, contentType = "General JSON Content", maxRetries = 4) {
  if (!apiKey) throw new Error("Claude API açarı daxil edilməyib.");

  let lastError = null;
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetchWithRetry('https://api.anthropic.com/v1/messages', {
        method: 'POST',
        headers: {
          'x-api-key': apiKey,
          'anthropic-version': '2023-06-01',
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          model: process.env.VITE_CLAUDE_MODEL || 'claude-opus-4.8',
          max_tokens: 4096,
          system: `You are an expert copywriter and synthesis engine. Your job is to output a final native translation for a ${contentType} segment in ${targetLangName} by evaluating raw translation and reviewer feedback.
You MUST output ONLY a valid raw JSON object. Do NOT wrap in markdown codeblocks (no \`\`\`json), do NOT write any introductory or closing text.

Required JSON Structure:
{
  "final_translation": "your final native translation here",
  "agent_notes": "a brief Azerbaijani explanation of why you made this choice or why reviews were useful",
  "discrepancy_percentage": 0-100
}`,
          messages: [
            { role: 'user', content: `Synthesize into valid JSON for target language: ${targetLangName}.

=== FULL CONTENT CONTEXT (For reference only) ===
${fullContext || "N/A"}
=== END CONTEXT ===

TARGET SEGMENT TO SYNTHESIZE:
Original English: "${original}"
DeepL Translation: "${deeplText}"
Gemini Feedback: "${geminiReview}"
OpenAI Feedback: "${openaiReview}"

Ensure all HTML tags, styles, and template variables (like {{$username}}, {{name}}, {count}) are 100% preserved. Respond ONLY with the raw JSON object.` }
          ]
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Claude API Xətası: ${response.status} - ${errorText}`);
      }

      const data = await response.json();
      const rawText = data.content?.[0]?.text?.trim() || "";

      // Safe robust JSON Parsing
      const parsed = safeParseJson(rawText);
      if (parsed && typeof parsed.final_translation === 'string') {
        return {
          final_translation: parsed.final_translation,
          agent_notes: parsed.agent_notes || "Claude tərəfindən müvəffəqiyyətlə sintez edildi.",
          discrepancy_percentage: typeof parsed.discrepancy_percentage === 'number' ? parsed.discrepancy_percentage : 0,
          hasError: false
        };
      }
      console.warn("Claude raw output parsing failed:", rawText);
      throw new Error(`Claude cavabında etibarlı JSON obyekti tapılmadı.`);
    } catch (err) {
      console.warn(`Claude Sintez Cəhdi ${attempt}/${maxRetries} xətası: ${err.message}`);
      lastError = err;
      if (attempt < maxRetries) {
        await new Promise(r => setTimeout(r, 1000 * attempt));
      }
    }
  }

  // If retries failed, return warning status so user can trigger manual retry
  return {
    final_translation: deeplText,
    agent_notes: `⚠️ Claude Sintez Xətası (${lastError ? lastError.message : "JSON alına bilmədi"}). [Yenidən Sına] düyməsinə klikləyin.`,
    discrepancy_percentage: 0,
    hasError: true
  };
}

// -------------------------------------------------------------
// POST Route for Segment Translation
// -------------------------------------------------------------
app.post('/api/translate-segment', async (req, res) => {
  const { segment, targetLang, targetLangName, fullContext, contentType, apiKeys } = req.body;
  const originalText = segment.original;

  const resolvedKeys = {
    deepl: apiKeys?.deepl || process.env.VITE_DEEPL_KEY || process.env.DEEPL_API_KEY,
    gemini: apiKeys?.gemini || process.env.VITE_GEMINI_KEY || process.env.GEMINI_API_KEY,
    openai: apiKeys?.openai || process.env.VITE_OPENAI_KEY || process.env.OPENAI_API_KEY,
    claude: apiKeys?.claude || process.env.VITE_CLAUDE_KEY || process.env.CLAUDE_API_KEY
  };

  try {
    if (!resolvedKeys.deepl) {
      return res.status(400).json({ success: false, error: "DeepL API açarı daxil edilməyib." });
    }
    if (!resolvedKeys.claude) {
      return res.status(400).json({ success: false, error: "Claude API açarı daxil edilməyib." });
    }

    // 1. Initial translation (DeepL)
    const deeplText = (await translateDeepL([originalText], targetLang, resolvedKeys.deepl))[0];

    // 2. Parallel peer review (Gemini / OpenAI)
    const [geminiReview, openaiReview] = await Promise.all([
      resolvedKeys.gemini ? reviewGemini(originalText, deeplText, targetLangName, resolvedKeys.gemini, fullContext, contentType) : Promise.resolve("BYPASSED"),
      resolvedKeys.openai ? reviewOpenAI(originalText, deeplText, targetLangName, resolvedKeys.openai, fullContext, contentType) : Promise.resolve("BYPASSED")
    ]);

    // 3. Synthesis (Claude with 4 Retries)
    const claudeResult = await synthesizeClaude(
      originalText,
      deeplText,
      geminiReview,
      openaiReview,
      targetLangName,
      resolvedKeys.claude,
      fullContext,
      contentType,
      4
    );

    res.json({
      success: true,
      deepl: deeplText,
      gemini: geminiReview,
      openai: openaiReview,
      claude: claudeResult
    });
  } catch (error) {
    console.error("Server API translation error:", error);
    res.status(500).json({ success: false, error: error.message || "Tərcümə zamanı server xətası." });
  }
});

// -------------------------------------------------------------
// POST Route for Granular Single-Step Retries
// -------------------------------------------------------------
app.post('/api/retry-step', async (req, res) => {
  const { step, originalText, deeplText, geminiReview, openaiReview, targetLang, targetLangName, fullContext, contentType, apiKeys } = req.body;

  const resolvedKeys = {
    deepl: apiKeys?.deepl || process.env.VITE_DEEPL_KEY || process.env.DEEPL_API_KEY,
    gemini: apiKeys?.gemini || process.env.VITE_GEMINI_KEY || process.env.GEMINI_API_KEY,
    openai: apiKeys?.openai || process.env.VITE_OPENAI_KEY || process.env.OPENAI_API_KEY,
    claude: apiKeys?.claude || process.env.VITE_CLAUDE_KEY || process.env.CLAUDE_API_KEY
  };

  try {
    if (step === 'deepl') {
      const newDeepl = (await translateDeepL([originalText], targetLang, resolvedKeys.deepl))[0];
      return res.json({ success: true, deepl: newDeepl });
    } else if (step === 'gemini') {
      const newGemini = await reviewGemini(originalText, deeplText, targetLangName, resolvedKeys.gemini, fullContext, contentType);
      return res.json({ success: true, gemini: newGemini });
    } else if (step === 'openai') {
      const newOpenAI = await reviewOpenAI(originalText, deeplText, targetLangName, resolvedKeys.openai, fullContext, contentType);
      return res.json({ success: true, openai: newOpenAI });
    } else if (step === 'claude') {
      const newClaude = await synthesizeClaude(originalText, deeplText, geminiReview, openaiReview, targetLangName, resolvedKeys.claude, fullContext, contentType, 4);
      return res.json({ success: true, claude: newClaude });
    } else {
      return res.status(400).json({ success: false, error: "Nəzərdə tutulmayan addım tipi." });
    }
  } catch (err) {
    console.error(`Retry step ${step} error:`, err);
    return res.status(500).json({ success: false, error: err.message });
  }
});

// -------------------------------------------------------------
// Central Storage API for Multi-Browser Task Synchronization
// -------------------------------------------------------------
const TASKS_FILE_PATH = path.join(process.cwd(), 'data_tasks.json');

app.get('/api/tasks', (req, res) => {
  try {
    if (fs.existsSync(TASKS_FILE_PATH)) {
      const data = fs.readFileSync(TASKS_FILE_PATH, 'utf8');
      return res.json(JSON.parse(data));
    }
    return res.json(null);
  } catch (err) {
    console.error("Error reading tasks file:", err);
    return res.status(500).json({ error: "Failed to read tasks" });
  }
});

app.post('/api/tasks', (req, res) => {
  try {
    const { tasks } = req.body;
    if (Array.isArray(tasks)) {
      fs.writeFileSync(TASKS_FILE_PATH, JSON.stringify(tasks, null, 2), 'utf8');
      return res.json({ success: true, count: tasks.length });
    }
    return res.status(400).json({ error: "Invalid tasks format" });
  } catch (err) {
    console.error("Error saving tasks file:", err);
    return res.status(500).json({ error: "Failed to save tasks" });
  }
});

// -------------------------------------------------------------
// Formbricks API Proxy
// -------------------------------------------------------------

app.get('/api/formbricks/survey/:id', async (req, res) => {
  try {
    const surveyId = req.params.id;
    const apiKey = process.env.Formbricks_API;
    
    if (!apiKey) {
      return res.status(400).json({ error: "Formbricks API key is missing in .env.local" });
    }

    const response = await fetch(`${FORMBRICKS_BASE_URL}/api/v1/management/surveys/${surveyId}`, {
      method: 'GET',
      headers: {
        'x-api-key': apiKey,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      const errText = await response.text();
      return res.status(response.status).json({ error: `Formbricks fetch failed: ${response.status}`, details: errText });
    }

    const data = await response.json();
    return res.json(data);
  } catch (err) {
    console.error("Error fetching formbricks survey:", err);
    return res.status(500).json({ error: "Failed to fetch survey from Formbricks" });
  }
});

app.put('/api/formbricks/survey/:id', async (req, res) => {
  try {
    const surveyId = req.params.id;
    const surveyData = req.body;
    const apiKey = process.env.Formbricks_API;

    if (!apiKey) {
      return res.status(400).json({ error: "Formbricks API key is missing in .env.local" });
    }

    // Clean payload to comply with Formbricks Zod validation
    if (surveyData && typeof surveyData === 'object') {
      if (surveyData.blocks && surveyData.questions) {
        delete surveyData.questions; // Formbricks forbids sending both questions and blocks
      }

      // Collect all active language codes if present
      const activeCodes = (surveyData.languages || [])
        .filter(l => l.enabled !== false)
        .map(l => l.language?.code || l.code)
        .filter(Boolean);

      // Recursive helper to fill empty/missing language entries with default fallback
      const fillMissingLangs = (obj) => {
        if (!obj || typeof obj !== 'object') return;
        if (typeof obj.default === 'string') {
          for (const code of activeCodes) {
            if (!obj[code] || (typeof obj[code] === 'string' && !obj[code].trim())) {
              obj[code] = obj.default;
            }
          }
        }
        for (const k in obj) {
          if (typeof obj[k] === 'object') {
            fillMissingLangs(obj[k]);
          }
        }
      };

      if (activeCodes.length > 0) {
        fillMissingLangs(surveyData);
      }

      delete surveyData.createdAt;
      delete surveyData.updatedAt;
      delete surveyData.createdBy;
      delete surveyData.segment;
      delete surveyData.triggers;
      delete surveyData.followUps;
      delete surveyData.languages; // Read-only metadata that fails Zod date validation
    }

    const response = await fetch(`${FORMBRICKS_BASE_URL}/api/v1/management/surveys/${surveyId}`, {
      method: 'PUT',
      headers: {
        'x-api-key': apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(surveyData)
    });

    if (!response.ok) {
      const errText = await response.text();
      return res.status(response.status).json({ error: `Formbricks update failed: ${response.status}`, details: errText });
    }

    const text = await response.text();
    const data = text ? JSON.parse(text) : { success: true };
    return res.json(data);
  } catch (err) {
    console.error("Error updating formbricks survey:", err);
    return res.status(500).json({ error: "Failed to update survey in Formbricks" });
  }
});

// Serve frontend build in production / Hugging Face Spaces
const __dirname = path.resolve();
if (fs.existsSync(path.join(__dirname, 'dist'))) {
  app.use(express.static(path.join(__dirname, 'dist')));
  app.get('*', (req, res, next) => {
    if (req.path.startsWith('/api')) return next();
    res.sendFile(path.join(__dirname, 'dist', 'index.html'));
  });
}

app.listen(PORT, () => {
  console.log(`Backend server secure proxy is running on port ${PORT}`);
});