/**
 * Test AlloyDB Connection
 * 
 * Run with: npx tsx scripts/test-alloydb.ts
 */

import { getAlloyDbClient, checkAlloyDbHealth, executeQuery } from '../lib/db/alloydb';

async function testConnection() {
  console.log('🧪 Testing AlloyDB Connection\n');
  console.log('='.repeat(50));
  
  try {
    // Test 1: Health check
    console.log('\n1️⃣ Health Check...');
    const healthy = await checkAlloyDbHealth();
    
    if (!healthy) {
      console.error('❌ Health check failed!');
      console.log('\nTroubleshooting:');
      console.log('  1. Is AlloyDB Auth Proxy running?');
      console.log('  2. Check environment variables in .env.local');
      console.log('  3. Verify service account has permissions');
      process.exit(1);
    }
    
    console.log('✅ Health check passed!');
    
    // Test 2: PostgreSQL version
    console.log('\n2️⃣ PostgreSQL Version...');
    const versionResult = await executeQuery<{ version: string }>('SELECT version()');
    console.log('✅ Version:', versionResult.rows[0].version.split(',')[0]);
    
    // Test 3: Check extensions
    console.log('\n3️⃣ Checking Extensions...');
    const extResult = await executeQuery<{ extname: string }>(
      "SELECT extname FROM pg_extension WHERE extname IN ('vector', 'uuid-ossp')"
    );
    
    const installedExts = extResult.rows.map(r => r.extname);
    
    if (installedExts.includes('vector')) {
      console.log('✅ pgvector extension installed');
    } else {
      console.log('❌ pgvector extension NOT installed');
      console.log('   Run: CREATE EXTENSION vector;');
    }
    
    if (installedExts.includes('uuid-ossp')) {
      console.log('✅ uuid-ossp extension installed');
    } else {
      console.log('❌ uuid-ossp extension NOT installed');
      console.log('   Run: CREATE EXTENSION "uuid-ossp";');
    }
    
    // Test 4: Check for knowledge_chunks table
    console.log('\n4️⃣ Checking Tables...');
    const tableResult = await executeQuery<{ table_name: string }>(
      `SELECT table_name 
       FROM information_schema.tables 
       WHERE table_schema = 'public' 
       AND table_name = 'knowledge_chunks'`
    );
    
    if (tableResult.rows.length > 0) {
      console.log('✅ knowledge_chunks table exists');
      
      // Check indexes
      const indexResult = await executeQuery<{ indexname: string }>(
        `SELECT indexname 
         FROM pg_indexes 
         WHERE tablename = 'knowledge_chunks'`
      );
      
      console.log(`✅ ${indexResult.rows.length} indexes created:`);
      indexResult.rows.forEach(row => {
        console.log(`   - ${row.indexname}`);
      });
      
      // Count chunks
      const countResult = await executeQuery<{ count: string }>(
        'SELECT COUNT(*) as count FROM knowledge_chunks'
      );
      const count = parseInt(countResult.rows[0].count, 10);
      console.log(`✅ Total chunks: ${count}`);
      
    } else {
      console.log('⚠️  knowledge_chunks table NOT found');
      console.log('   Run the schema file:');
      console.log('   psql "host=127.0.0.1 port=5432 dbname=vibn user=YOUR_SA" \\');
      console.log('     -f lib/db/knowledge-chunks-schema.sql');
    }
    
    // Test 5: Test vector operations (if table exists and vector extension installed)
    if (tableResult.rows.length > 0 && installedExts.includes('vector')) {
      console.log('\n5️⃣ Testing Vector Operations...');
      
      try {
        // Create a test embedding
        const testEmbedding = Array.from({ length: 768 }, () => Math.random());
        
        // Test vector similarity query (should not error even with empty table)
        await executeQuery(
          `SELECT id 
           FROM knowledge_chunks 
           ORDER BY embedding <=> $1::vector 
           LIMIT 1`,
          [JSON.stringify(testEmbedding)]
        );
        
        console.log('✅ Vector similarity queries working!');
      } catch (error) {
        console.log('❌ Vector operations failed:', error);
      }
    }
    
    console.log('\n' + '='.repeat(50));
    console.log('🎉 AlloyDB is ready to use!');
    console.log('='.repeat(50));
    console.log('\nNext steps:');
    console.log('  1. Start your app: npm run dev');
    console.log('  2. Import a knowledge item to test chunking');
    console.log('  3. Send a chat message to test vector search');
    console.log('');
    
    process.exit(0);
    
  } catch (error) {
    console.error('\n❌ Connection failed!');
    console.error('Error:', error instanceof Error ? error.message : String(error));
    console.log('\nTroubleshooting:');
    console.log('  1. Check .env.local has correct values');
    console.log('  2. Ensure AlloyDB Auth Proxy is running:');
    console.log('     alloydb-auth-proxy --credentials-file=~/vibn-alloydb-key.json --port=5432 YOUR_INSTANCE_URI');
    console.log('  3. Verify service account permissions');
    console.log('  4. Check network connectivity');
    console.log('');
    process.exit(1);
  }
}

// Run test
console.log('Starting AlloyDB connection test...\n');
console.log('Environment:');
console.log('  ALLOYDB_HOST:', process.env.ALLOYDB_HOST);
console.log('  ALLOYDB_PORT:', process.env.ALLOYDB_PORT);
console.log('  ALLOYDB_DATABASE:', process.env.ALLOYDB_DATABASE);
console.log('  ALLOYDB_USER:', process.env.ALLOYDB_USER?.substring(0, 30) + '...');
console.log('');

testConnection();

