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

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

const SYSTEM_PROMPTS: Record<string, (ctx: any) => string> = {
  content_message: (ctx) => `
You are an expert WhatsApp chatbot copywriter for a healthcare clinic.
Write a warm, concise WhatsApp message for the node titled "${ctx.nodeLabel}" inside a flow called "${ctx.treeName}".
Rules:
- Max 300 characters
- Use {{name}}, {{treatment}}, {{clinic}}, {{date}}, {{time}} where natural
- WhatsApp formatting: *bold*, _italic_
- Empathetic and professional tone
- No placeholder brackets like [X] — write the real text
Return ONLY the message text, nothing else.`.trim(),

  content_buttons: (ctx) => `
You are an expert WhatsApp chatbot copywriter for a healthcare clinic.
Write a SHORT message (max 150 chars) to accompany interactive buttons in a node called "${ctx.nodeLabel}" in flow "${ctx.treeName}".
Use {{name}} if helpful. Be friendly and clear.
Return ONLY the message text, nothing else.`.trim(),

  aiSystemPrompt: (ctx) => `
You are an expert conversational AI designer for healthcare chatbots.
Write a Gemini system prompt for an AI response node called "${ctx.nodeLabel}" in a chatbot flow named "${ctx.treeName}".
The prompt instructs the AI how to respond to a patient's WhatsApp message.
Use placeholders like {{name}}, {{clinic}}, {{treatment}}, {{date}} naturally.
Return ONLY the system prompt text (2-4 sentences), nothing else.`.trim(),

  aiConditionPrompt: (ctx) => `
You are an expert conversational AI designer for healthcare chatbots.
Write a classification prompt for a condition/routing node called "${ctx.nodeLabel}" in flow "${ctx.treeName}".
This prompt instructs the AI to read a patient's WhatsApp message and decide which branch to route them to.
Return ONLY the classification prompt (1-3 sentences), nothing else.`.trim(),
};

export async function POST(req: NextRequest) {
  try {
    if (!process.env.GEMINI_API_KEY) {
      return NextResponse.json({ error: "GEMINI_API_KEY not configured in .env" }, { status: 500 });
    }

    const { nodeKind, nodeLabel, field, currentContent, treeName } = await req.json();

    const promptKey = field === "content" ? `content_${nodeKind}` : field;
    const systemFn = SYSTEM_PROMPTS[promptKey];
    if (!systemFn) {
      return NextResponse.json(
        { error: `No AI prompt defined for field "${field}" on kind "${nodeKind}"` },
        { status: 400 }
      );
    }

    const systemPrompt = systemFn({ nodeLabel, treeName, nodeKind });
    const userMsg = currentContent
      ? `Current content (improve or replace):\n${currentContent}`
      : `Generate fresh content for this ${nodeKind} node.`;

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

    const response = await model.generateContent({
      contents: [{ role: "user", parts: [{ text: userMsg }] }],
      generationConfig: { maxOutputTokens: 400 },
    });

    const result = response.response.text().trim();

    return NextResponse.json({ result });
  } catch (err: any) {
    console.error("AI generate error:", err);
    return NextResponse.json({ error: err.message ?? "Unknown error" }, { status: 500 });
  }
}
