/**
 * POST /api/docs/chat — RAG chatbot powered by Perplexity AI.
 *
 * Sends all project docs as context + user question to Perplexity,
 * returns a streaming or complete response.
 *
 * Body: { question: string, history?: Array<{ role: string, content: string }> }
 */

import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getAllDocsContent } from '@/lib/docs';
const PERPLEXITY_API_KEY = process.env.PERPLEXITY_API_KEY;
const PERPLEXITY_URL = 'https://api.perplexity.ai/chat/completions';
const SYSTEM_PROMPT = `You are Platform Admin Assistant — an expert on the platform project.
You answer questions about the project's architecture, devops runbooks, deployment,
billing, Stripe setup, mobile apps, desktop app, microservices, testing, and any
other topic covered in the project documentation.
You have access to ALL project documentation below. Use it to give accurate,
specific answers. Reference document names when citing information.
If the docs don't contain the answer, say so clearly.
Be concise, use markdown formatting, and include code snippets when helpful.
--- PROJECT DOCUMENTATION ---
`;
export async function POST(req: NextRequest) {
  if (!PERPLEXITY_API_KEY) {
    return NextResponse.json({ error: 'PERPLEXITY_API_KEY not configured' }, { status: 500 });
  }
  const body = await req.json();
  const { question, history = [] } = body;
  if (!question || typeof question !== 'string') {
    return NextResponse.json({ error: "Missing 'question' field" }, { status: 400 });
  }
  // Build context from all docs
  const docsContext = getAllDocsContent(3000);
  const systemMessage = SYSTEM_PROMPT + docsContext;
  // Build messages array
  const messages = [
    { role: 'system', content: systemMessage },
    ...history.slice(-6), // Keep last 6 messages for context window
    { role: 'user', content: question },
  ];
  try {
    const response = await fetch(PERPLEXITY_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${PERPLEXITY_API_KEY}`,
      },
      body: JSON.stringify({
        model: 'sonar',
        messages,
        max_tokens: 2048,
        temperature: 0.2,
      }),
    });
    if (!response.ok) {
      const err = await response.text();
      logError('Perplexity API error', err, { status: response.status });
      return NextResponse.json(
        { error: `Perplexity API error: ${response.status}` },
        { status: 502 }
      );
    }
    const data = await response.json();
    const answer = data.choices?.[0]?.message?.content ?? 'No response generated.';
    return NextResponse.json({
      answer,
      model: data.model,
      usage: data.usage,
    });
  } catch (err) {
    logError('Perplexity chat error', err);
    return NextResponse.json({ error: 'Failed to reach Perplexity API' }, { status: 502 });
  }
}
