/* eslint-disable */
// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const { history, prompt, sender } = body;

    // Environment variables routing
    const engine = process.env.OMNIBRAIN_ENGINE || "XCU_DEEP_CORE";
    const openaiKey = process.env.OPENAI_API_KEY;
    const geminiKey = process.env.GEMINI_API_KEY;
    const grokKey = process.env.GROK_API_KEY;
    
    // Proxy URLs for State Audit Compliance
    const openaiUrl = process.env.OPENAI_API_URL || "http://127.0.0.1:11434/v1/chat/completions";
    const geminiUrl = process.env.GEMINI_API_URL || "http://127.0.0.1:11434/v1/chat/completions";
    const grokUrl = process.env.GROK_API_URL || "http://127.0.0.1:11434/v1/chat/completions";

    // Format history for context
    const historyText = history.map((m: any) => `${m.sender}: ${m.text}`).join('\n');
    const systemPrompt = 'You are Omni-Brain, an advanced AI telepathic observer inside an End-to-End Encrypted XCU Ultra chat room. Provide concise, highly analytical, and awe-inspiring responses in Indonesian. Use terms like "Jaringan Kuantum", "Matriks Telepati", etc.';
    const userPrompt = `[Decrypted Context - Top Secret]\n${historyText}\n\nUser [${sender}] commands: ${prompt}`;

    let reply = "";

    // DYNAMIC ROUTING ENGINE
    if (engine === "OPENAI" && openaiKey) {
      const response = await fetch(openaiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${openaiKey}`
        },
        body: JSON.stringify({
          model: 'gpt-4o',
          messages: [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: userPrompt }
          ],
          max_tokens: 300
        })
      });
      const data = await response.json();
      reply = data.choices?.[0]?.message?.content || "";
      
    } else if (engine === "GEMINI" && geminiKey) {
      const response = await fetch(geminiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contents: [{ parts: [{ text: `${systemPrompt}\n\n${userPrompt}` }] }]
        })
      });
      const data = await response.json();
      reply = data.candidates?.[0]?.content?.parts?.[0]?.text || "";
      
    } else if (engine === "GROK" && grokKey) {
      const response = await fetch(grokUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${grokKey}`
        },
        body: JSON.stringify({
          model: 'grok-beta',
          messages: [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: userPrompt }
          ]
        })
      });
      const data = await response.json();
      reply = data.choices?.[0]?.message?.content || "";
      
    } else {
      // 1000% DEFAULT FALLBACK: XCU DEEP-CORE LOCAL LLM (OLLAMA / Llama3)
      // Jaringan Air-Gapped Sovereign murni
      try {
        const response = await fetch('http://127.0.0.1:11434/v1/chat/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            model: 'llama3', // Atau deepseek-coder, mistral, dll.
            messages: [
              { role: 'system', content: systemPrompt },
              { role: 'user', content: userPrompt }
            ]
          })
        });
        const data = await response.json();
        reply = data.choices?.[0]?.message?.content || "";
      } catch (e) {
        return NextResponse.json({ reply: "Sistem XCU Deep-Core LLM terputus. Pastikan daemon Ollama berjalan di peladen (127.0.0.1:11434)." }, { status: 200 });
      }
    }

    if (reply) {
      return NextResponse.json({ reply }, { status: 200 });
    } else {
      return NextResponse.json({ reply: "OmniBrain mengalami anomali dalam matriks kuantum. Gagal memproses data." }, { status: 200 });
    }

  } catch (error) {
    console.error('OmniBrain Error:', error);
    return NextResponse.json({ reply: "Terjadi distorsi telepatik saat memproses neural-link." }, { status: 200 });
  }
}
