require('dotenv').config({ path: '/root/Apps/Camila/.env' });
const { Pool } = require('pg');

async function testAll() {
  const results = [];

  // 1. Test PostgreSQL Database
  try {
    const pool = new Pool({ connectionString: process.env.DATABASE_URL });
    const res = await pool.query('SELECT NOW() as now, current_database() as db;');
    await pool.end();
    results.push({
      service: 'PostgreSQL (Supabase DB)',
      status: '✅ OK',
      details: `Conectado ao banco "${res.rows[0].db}" em ${res.rows[0].now}`
    });
  } catch (err) {
    results.push({
      service: 'PostgreSQL (Supabase DB)',
      status: '❌ ERRO',
      details: err.message
    });
  }

  // 2. Test MiniMax
  try {
    const minmBase = (process.env.MINIMAX_API_BASE || 'https://api.minimax.io/v1').replace(/\/v1\/?$/, '');
    const model = process.env.MINIMAX_MODEL || 'MiniMax-M3';
    const res = await fetch(`${minmBase}/v1/chat/completions`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.MINIMAX_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: model,
        messages: [{ role: 'user', content: 'Diga "ok"' }],
        max_tokens: 10
      })
    });
    if (res.ok) {
      const data = await res.json();
      const answer = data.choices?.[0]?.message?.content || JSON.stringify(data);
      results.push({
        service: `MiniMax (${model})`,
        status: '✅ OK',
        details: `Resposta: "${answer.trim()}"`
      });
    } else {
      const txt = await res.text();
      results.push({
        service: `MiniMax (${model})`,
        status: `❌ HTTP ${res.status}`,
        details: txt
      });
    }
  } catch (err) {
    results.push({
      service: 'MiniMax',
      status: '❌ ERRO',
      details: err.message
    });
  }

  // 3. Test Groq
  try {
    const model = process.env.GROQ_MODEL || 'llama-3.3-70b-versatile';
    const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.GROQ_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: model,
        messages: [{ role: 'user', content: 'Diga "ok"' }],
        max_tokens: 10
      })
    });
    if (res.ok) {
      const data = await res.json();
      const answer = data.choices?.[0]?.message?.content || JSON.stringify(data);
      results.push({
        service: `Groq (${model})`,
        status: '✅ OK',
        details: `Resposta: "${answer.trim()}"`
      });
    } else {
      const txt = await res.text();
      results.push({
        service: `Groq (${model})`,
        status: `❌ HTTP ${res.status}`,
        details: txt
      });
    }
  } catch (err) {
    results.push({
      service: 'Groq',
      status: '❌ ERRO',
      details: err.message
    });
  }

  // 4. Test OpenRouter
  try {
    const model = process.env.OPENROUTER_MODEL || 'openai/gpt-4.1-nano';
    const res = await fetch('https://openrouter.ai/api/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`,
        'HTTP-Referer': 'https://pedagog.app',
        'X-Title': 'Pedagog AI Test',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: model,
        messages: [{ role: 'user', content: 'Diga "ok"' }],
        max_tokens: 10
      })
    });
    if (res.ok) {
      const data = await res.json();
      const answer = data.choices?.[0]?.message?.content || JSON.stringify(data);
      results.push({
        service: `OpenRouter (${model})`,
        status: '✅ OK',
        details: `Resposta: "${answer.trim()}"`
      });
    } else {
      const txt = await res.text();
      results.push({
        service: `OpenRouter (${model})`,
        status: `❌ HTTP ${res.status}`,
        details: txt
      });
    }
  } catch (err) {
    results.push({
      service: 'OpenRouter',
      status: '❌ ERRO',
      details: err.message
    });
  }

  // 5. Test Google Gemini AI
  try {
    const model = process.env.GOOGLE_AI_MODEL || 'gemini-2.5-flash';
    const apiKey = process.env.GOOGLE_AI_API_KEY;
    const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        contents: [{ parts: [{ text: 'Diga "ok"' }] }]
      })
    });
    if (res.ok) {
      const data = await res.json();
      const answer = data.candidates?.[0]?.content?.parts?.[0]?.text || JSON.stringify(data);
      results.push({
        service: `Google Gemini (${model})`,
        status: '✅ OK',
        details: `Resposta: "${answer.trim()}"`
      });
    } else {
      const txt = await res.text();
      results.push({
        service: `Google Gemini (${model})`,
        status: `❌ HTTP ${res.status}`,
        details: txt
      });
    }
  } catch (err) {
    results.push({
      service: 'Google Gemini',
      status: '❌ ERRO',
      details: err.message
    });
  }

  console.log(JSON.stringify(results, null, 2));
}

testAll();
