const axios = require('axios');
require('dotenv').config();

async function testChatAPI() {
  console.log('🧪 Testing Azure OpenAI Chat API (GPT-5)...');

  const chatUrl = `${process.env.AZURE_OPENAI_CHAT_ENDPOINT}/openai/deployments/${process.env.AZURE_OPENAI_CHAT_DEPLOYMENT}/chat/completions?api-version=${process.env.AZURE_OPENAI_CHAT_API_VERSION}`;

  const requestBody = {
    messages: [
      {
        role: 'system',
        content: 'You are a helpful parenting assistant.'
      },
      {
        role: 'user',
        content: 'Say "Hello! Azure OpenAI Chat is working!" if you receive this.'
      }
    ],
    // temperature: 1, // GPT-5 only supports temperature=1 (default), so we omit it
    max_completion_tokens: 100, // GPT-5 uses max_completion_tokens instead of max_tokens
    reasoning_effort: process.env.AZURE_OPENAI_REASONING_EFFORT || 'medium',
  };

  try {
    const response = await axios.post(chatUrl, requestBody, {
      headers: {
        'api-key': process.env.AZURE_OPENAI_CHAT_API_KEY,
        'Content-Type': 'application/json',
      },
      timeout: 30000,
    });

    console.log('✅ SUCCESS! Chat API is working!\n');
    console.log('📊 Response Details:');
    console.log(`  Model: ${response.data.model}`);
    console.log(`  Finish Reason: ${response.data.choices[0].finish_reason}`);
    console.log(`  Prompt tokens: ${response.data.usage.prompt_tokens}`);
    console.log(`  Completion tokens: ${response.data.usage.completion_tokens}`);
    console.log(`  Reasoning tokens: ${response.data.usage.reasoning_tokens || 0}`);
    console.log(`  Total tokens: ${response.data.usage.total_tokens}\n`);

    return true;
  } catch (error) {
    console.log('❌ FAILED! Chat API test failed\n');
    logError(error, chatUrl);
    return false;
  }
}

async function testEmbeddingsAPI() {
  console.log('🧪 Testing Azure OpenAI Embeddings API...');

  const embeddingsUrl = `${process.env.AZURE_OPENAI_EMBEDDINGS_ENDPOINT}/openai/deployments/${process.env.AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT}/embeddings?api-version=${process.env.AZURE_OPENAI_EMBEDDINGS_API_VERSION}`;

  const requestBody = {
    input: 'Test embedding for parenting app'
  };

  try {
    const response = await axios.post(embeddingsUrl, requestBody, {
      headers: {
        'api-key': process.env.AZURE_OPENAI_EMBEDDINGS_API_KEY,
        'Content-Type': 'application/json',
      },
      timeout: 30000,
    });

    console.log('✅ SUCCESS! Embeddings API is working!\n');
    console.log('📊 Response Details:');
    console.log(`  Model: ${response.data.model}`);
    console.log(`  Embedding dimensions: ${response.data.data[0].embedding.length}`);
    console.log(`  Prompt tokens: ${response.data.usage.prompt_tokens}`);
    console.log(`  Total tokens: ${response.data.usage.total_tokens}\n`);

    return true;
  } catch (error) {
    console.log('❌ FAILED! Embeddings API test failed\n');
    logError(error, embeddingsUrl);
    return false;
  }
}

function logError(error, url) {
  if (error.response) {
    console.log('📋 Error Details:');
    console.log(`  Status: ${error.response.status} ${error.response.statusText}`);
    console.log(`  Error:`, JSON.stringify(error.response.data, null, 2));

    if (error.response.status === 401) {
      console.log('\n💡 Suggestion: Check if API key is correct');
    } else if (error.response.status === 404) {
      console.log('\n💡 Suggestion: Check if deployment name is correct');
    } else if (error.response.status === 429) {
      console.log('\n💡 Suggestion: Rate limit exceeded, wait a moment and try again');
    }
  } else if (error.request) {
    console.log('📋 Network Error:');
    console.log(`  Could not reach: ${url}`);
    console.log('💡 Suggestion: Check if endpoint is correct');
  } else {
    console.log('📋 Error:', error.message);
  }
  console.log();
}

async function testAzureOpenAI() {
  console.log('🔍 Testing All Azure OpenAI Services...\n');
  console.log('='.repeat(60));
  console.log('\n📋 Environment Variables:\n');

  console.log('Chat Service:');
  console.log(`  AI_PROVIDER: ${process.env.AI_PROVIDER}`);
  console.log(`  AZURE_OPENAI_ENABLED: ${process.env.AZURE_OPENAI_ENABLED}`);
  console.log(`  AZURE_OPENAI_CHAT_ENDPOINT: ${process.env.AZURE_OPENAI_CHAT_ENDPOINT}`);
  console.log(`  AZURE_OPENAI_CHAT_DEPLOYMENT: ${process.env.AZURE_OPENAI_CHAT_DEPLOYMENT}`);
  console.log(`  AZURE_OPENAI_CHAT_API_VERSION: ${process.env.AZURE_OPENAI_CHAT_API_VERSION}`);
  console.log(`  AZURE_OPENAI_CHAT_API_KEY: ${process.env.AZURE_OPENAI_CHAT_API_KEY ? '✅ Set' : '❌ Not Set'}`);
  console.log(`  AZURE_OPENAI_REASONING_EFFORT: ${process.env.AZURE_OPENAI_REASONING_EFFORT}\n`);

  console.log('Embeddings Service:');
  console.log(`  AZURE_OPENAI_EMBEDDINGS_ENDPOINT: ${process.env.AZURE_OPENAI_EMBEDDINGS_ENDPOINT}`);
  console.log(`  AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT: ${process.env.AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT}`);
  console.log(`  AZURE_OPENAI_EMBEDDINGS_API_VERSION: ${process.env.AZURE_OPENAI_EMBEDDINGS_API_VERSION}`);
  console.log(`  AZURE_OPENAI_EMBEDDINGS_API_KEY: ${process.env.AZURE_OPENAI_EMBEDDINGS_API_KEY ? '✅ Set' : '❌ Not Set'}\n`);

  console.log('Whisper Service (Voice):');
  console.log(`  AZURE_OPENAI_WHISPER_ENDPOINT: ${process.env.AZURE_OPENAI_WHISPER_ENDPOINT}`);
  console.log(`  AZURE_OPENAI_WHISPER_DEPLOYMENT: ${process.env.AZURE_OPENAI_WHISPER_DEPLOYMENT}`);
  console.log(`  AZURE_OPENAI_WHISPER_API_VERSION: ${process.env.AZURE_OPENAI_WHISPER_API_VERSION}`);
  console.log(`  AZURE_OPENAI_WHISPER_API_KEY: ${process.env.AZURE_OPENAI_WHISPER_API_KEY ? '✅ Set' : '❌ Not Set'}\n`);

  console.log('='.repeat(60));
  console.log();

  const results = {
    chat: false,
    embeddings: false,
    whisper: 'skipped'
  };

  // Test Chat API
  if (!process.env.AZURE_OPENAI_CHAT_API_KEY) {
    console.log('⚠️  Skipping Chat API - API key not configured\n');
  } else {
    results.chat = await testChatAPI();
  }

  // Test Embeddings API
  if (!process.env.AZURE_OPENAI_EMBEDDINGS_API_KEY) {
    console.log('⚠️  Skipping Embeddings API - API key not configured\n');
  } else {
    results.embeddings = await testEmbeddingsAPI();
  }

  // Whisper API requires audio file upload, so we skip it in this basic test
  console.log('🧪 Whisper API (Voice Transcription)...');
  console.log('ℹ️  Skipping - Requires audio file upload (tested separately)\n');

  console.log('='.repeat(60));
  console.log('\n📊 Test Summary:\n');
  console.log(`  Chat API (GPT-5): ${results.chat ? '✅ PASSED' : '❌ FAILED'}`);
  console.log(`  Embeddings API: ${results.embeddings ? '✅ PASSED' : '❌ FAILED'}`);
  console.log(`  Whisper API: ⏭️  SKIPPED (requires audio file)\n`);

  const allPassed = results.chat && results.embeddings;
  return allPassed;
}

// Run the test
testAzureOpenAI()
  .then((success) => {
    if (success) {
      console.log('✨ All testable services passed! Azure OpenAI is configured correctly.\n');
      process.exit(0);
    } else {
      console.log('⚠️  Some tests failed. Please check the configuration.\n');
      process.exit(1);
    }
  })
  .catch((error) => {
    console.log('❌ Unexpected error:', error.message);
    process.exit(1);
  });
