import { NextRequest, NextResponse } from 'next/server'; const CRAWL_SERVICE_URL = 'http://127.0.0.1:8000'; export async function POST(req: NextRequest) { try { const body = await req.json(); const { message, history } = body; console.log(`[Grok Debug API] Incoming body:`, JSON.stringify(body, null, 2)); const proxyPayload = { message, history: history || [], cookies: body.cookies || null, user_agent: body.userAgent || null }; console.log(`[Grok Debug API] Proxy payload:`, JSON.stringify(proxyPayload, null, 2)); const response = await fetch(`${CRAWL_SERVICE_URL}/grok/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(proxyPayload), }); if (!response.ok) { const errorText = await response.text(); console.error(`[Grok Debug API] Service error: ${response.status} ${errorText}`); try { // Try to parse detailed JSON error from FastAPI const errorJson = JSON.parse(errorText); return NextResponse.json(errorJson, { status: response.status }); } catch { // Fallback to text return NextResponse.json( { error: `Service error: ${response.status} - ${errorText}` }, { status: response.status } ); } } const data = await response.json(); return NextResponse.json(data); } catch (error: any) { console.error('[Grok Debug API] Internal error:', error); return NextResponse.json( { error: error.message || 'Internal Server Error' }, { status: 500 } ); } }