#!/usr/bin/env node
/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * TEST INSTALLATION OVERMIND-MCP
 * ═══════════════════════════════════════════════════════════════════════════════
 * Script de vérification de l'installation complète d'OverMind-MCP
 *
 * Usage:
 *   node scripts/test-installation.mjs
 * ═══════════════════════════════════════════════════════════════════════════════
 */

import { execSync } from 'child_process';
import { existsSync } from 'fs';
import { join } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const INSTALL_DIR = join(
  process.env.HOME || process.env.USERPROFILE || process.env.HOMEPATH,
  '.overmind'
);

function logSection(title) {
  console.log('\n╔══════════════════════════════════════════════════════════════════╗');
  console.log(`║  ${title.padEnd(64)} ║`);
  console.log('╚══════════════════════════════════════════════════════════════════╝');
}

function runCommand(cmd) {
  try {
    return execSync(cmd, { stdio: 'pipe', encoding: 'utf8' });
  } catch {
    return null;
  }
}

async function testInstallation() {
  console.log('╔══════════════════════════════════════════════════════════════════╗');
  console.log('║                                                                ║');
  console.log('║     🧪 TEST INSTALLATION OVERMIND-MCP                           ║');
  console.log('║                                                                ║');
  console.log('╚══════════════════════════════════════════════════════════════════╝');
  console.log('');

  const results = {
    docker: false,
    postgres: false,
    postgresMCP: false,
    configFiles: false,
    connection: false
  };

  // Test 1: Docker
  logSection('TEST 1: DOCKER');
  const dockerVersion = runCommand('docker --version');
  if (dockerVersion) {
    console.log('✅ Docker installé:', dockerVersion.trim());
    results.docker = true;
  } else {
    console.log('❌ Docker NON installé');
  }

  // Test 2: PostgreSQL Container
  logSection('TEST 2: POSTGRESQL CONTAINER');
  const postgresContainer = runCommand('docker ps --filter "name=postgres" --format "{{.Names}}"');
  if (postgresContainer) {
    console.log('✅ PostgreSQL container actif:', postgresContainer.trim());
    results.postgres = true;
  } else {
    console.log('❌ PostgreSQL container NON actif');
  }

  // Test 3: overmind-postgres-mcp
  logSection('TEST 3: OVERMIND-POSTGRES-MCP');
  const postgresMCP = runCommand('npm list -g overmind-postgres-mcp');
  if (postgresMCP && postgresMCP.includes('overmind-postgres-mcp')) {
    console.log('✅ overmind-postgres-mcp installé');
    results.postgresMCP = true;
  } else {
    console.log('❌ overmind-postgres-mcp NON installé');
  }

  // Test 4: Fichiers de configuration
  logSection('TEST 4: FICHIERS DE CONFIGURATION');
  const envFile = join(INSTALL_DIR, '.env');
  const postgresEnvFile = join(INSTALL_DIR, '.env.postgres');
  const mcpFile = join(INSTALL_DIR, '.mcp.json');

  const filesExist = existsSync(envFile) && existsSync(postgresEnvFile) && existsSync(mcpFile);
  if (filesExist) {
    console.log('✅ Fichiers de configuration créés:');
    console.log('   • .env');
    console.log('   • .env.postgres');
    console.log('   • .mcp.json');
    results.configFiles = true;
  } else {
    console.log('❌ Fichiers de configuration manquants');
  }

  // Test 5: Connexion PostgreSQL
  logSection('TEST 5: CONNEXION POSTGRESQL');
  if (results.postgres) {
    try {
      const pgVersion = execSync('docker exec overmind-postgres-pgvector psql -U postgres -t -c "SELECT version();"');
      if (pgVersion) {
        console.log('✅ Connexion PostgreSQL réussie');
        results.connection = true;
      }
    } catch {
      console.log('❌ Connexion PostgreSQL échouée');
    }
  } else {
    console.log('⏭️  Test ignoré (PostgreSQL non actif)');
  }

  // Résultat final
  logSection('RÉSULTAT FINAL');
  const totalTests = Object.keys(results).length;
  const passedTests = Object.values(results).filter(Boolean).length;

  console.log(`Tests passés: ${passedTests}/${totalTests}`);
  console.log('');

  if (passedTests === totalTests) {
    console.log('🎉 INSTALLATION PARFAITE ! OverMind-MCP est prêt à l\'emploi.');
    console.log('');
    console.log('📋 Prochaines étapes:');
    console.log('   1. Créez votre premier agent: overmind create-agent');
    console.log('   2. Listez les agents: overmind list-agents');
    console.log('   3. Testez la mémoire: overmind memory-store "Test"');
  } else {
    console.log('⚠️  CERTAINS TESTS ONT ÉCHOUÉ. Vérifiez les erreurs ci-dessus.');
    console.log('');
    console.log('💡 Solutions possibles:');
    if (!results.docker) {
      console.log('   • Installez Docker: https://www.docker.com/products/docker-desktop/');
    }
    if (!results.postgres) {
      console.log('   • Démarrez PostgreSQL: overmind-postgres up');
    }
    if (!results.postgresMCP) {
      console.log('   • Installez le MCP: npm install -g overmind-postgres-mcp');
    }
    if (!results.configFiles) {
      console.log('   • Lancez: npm install -g overmind-mcp');
    }
  }
}

// Run tests
testInstallation().catch(error => {
  console.error('❌ ERREUR:', error.message);
  process.exit(1);
});