import { NextRequest, NextResponse } from "next/server";
import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);

export async function POST(req: NextRequest) {
  const { nodes, targetLanguage = "Arabic" } = await req.json();

  const translatableNodes = nodes.filter((n: any) =>
    ["message", "buttons", "ai_response", "condition", "save_var", "retry"].includes(n.data?.kind)
  );

  if (translatableNodes.length === 0) {
    return NextResponse.json({ nodes });
  }

  // Build a single batch prompt to translate everything in one API call
  const batch = translatableNodes.map((n: any, i: number) => {
    const d = n.data;
    const fields: Record<string, string> = {};
    if (d.content)          fields.content         = d.content;
    if (d.aiSystemPrompt)   fields.aiSystemPrompt  = d.aiSystemPrompt;
    if (d.aiConditionPrompt)fields.aiConditionPrompt = d.aiConditionPrompt;
    if (d.retryMessage)     fields.retryMessage    = d.retryMessage;
    if (d.varPrompt)        fields.varPrompt       = d.varPrompt;
    if (d.label)            fields.label           = d.label;
    if (d.buttons)          fields.buttons         = JSON.stringify(d.buttons);
    if (d.branches)         fields.branches        = JSON.stringify(d.branches);
    return { index: i, nodeId: n.id, kind: d.kind, fields };
  });

  const systemPrompt = `You are a professional medical/healthcare translator.
Translate all text to ${targetLanguage}.
- Keep {{name}}, {{treatment}}, {{clinic}}, {{date}}, {{time}}, {{memory.*}} template variables exactly as-is
- Keep emoji as-is
- Keep WhatsApp *bold* and _italic_ formatting
- Translate button labels (inside the "text" and "label" fields in JSON)
- For Arabic: use right-to-left friendly, formal but warm tone
- Respond with ONLY a JSON array matching the input structure, with translated text values`;

  const model = genAI.getGenerativeModel({
    model: "gemini-2.0-flash",
    systemInstruction: systemPrompt,
  });

  const response = await model.generateContent({
    contents: [{
      role: "user",
      parts: [{ text: `Translate these chatbot node fields to ${targetLanguage}:\n${JSON.stringify(batch, null, 2)}` }],
    }],
    generationConfig: { maxOutputTokens: 4000 },
  });

  const raw = response.response.text().trim();
  const jsonMatch = raw.match(/\[[\s\S]*\]/);
  if (!jsonMatch) return NextResponse.json({ error: "Translation failed" }, { status: 500 });

  const translated: any[] = JSON.parse(jsonMatch[0]);

  // Merge translated fields back into the original nodes
  const updatedNodes = nodes.map((n: any) => {
    const translation = translated.find((t: any) => t.nodeId === n.id);
    if (!translation) return n;

    const f = translation.fields;
    const newData = { ...n.data };
    if (f.content)           newData.content          = f.content;
    if (f.aiSystemPrompt)    newData.aiSystemPrompt   = f.aiSystemPrompt;
    if (f.aiConditionPrompt) newData.aiConditionPrompt= f.aiConditionPrompt;
    if (f.retryMessage)      newData.retryMessage     = f.retryMessage;
    if (f.varPrompt)         newData.varPrompt        = f.varPrompt;
    if (f.label)             newData.label            = f.label;
    if (f.buttons) {
      try { newData.buttons = JSON.parse(f.buttons); } catch {}
    }
    if (f.branches) {
      try { newData.branches = JSON.parse(f.branches); } catch {}
    }
    return { ...n, data: newData };
  });

  return NextResponse.json({ nodes: updatedNodes, translatedCount: translated.length });
}
