import { NextResponse } from "next/server";
import { runSiteMenteVoiceTurn } from "../../../../lib/ai/siteMenteAgent";

export const runtime = "nodejs";

// Vapi webhook payload types
interface VapiMessage {
  type: string;
  role?: string;
  transcript?: string;
}

interface VapiCall {
  id: string;
}

interface VapiWebhookPayload {
  message: VapiMessage;
  call: VapiCall;
}

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as VapiWebhookPayload;
    
    // Extract transcript from Vapi's format
    const message = body.message;
    
    // Only process final transcripts
    if (!message || message.type !== "transcript" || !message.transcript) {
      // Return empty response for non-transcript messages
      return NextResponse.json({ results: [] });
    }

    const transcript = message.transcript;
    
    // Call MiniMax brain
    const response = await runSiteMenteVoiceTurn({
      transcript: transcript,
    });

    // Return in Vapi's expected format
    return NextResponse.json({
      results: [
        {
          result: response.reply,
        },
      ],
    });

  } catch (error) {
    console.error("[SiteMente][Vapi] Voice route failed", error);
    return NextResponse.json(
      { error: "Failed to generate voice response." },
      { status: 500 }
    );
  }
}
