#!/usr/bin/env node
/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * OVERMIND-MCP - INSTALLATION AUTOMATIQUE (POST-INSTALL)
 * ═══════════════════════════════════════════════════════════════════════════════
 * Ce script est exécuté automatiquement après npm install -g
 * Il installe et configure TOUT :
 * - Docker Desktop (vérification)
 * - PostgreSQL + pgvector (si absent)
 * - Infrastructure complète
 * - Invite l'utilisateur à voir les services dans Docker Desktop
 * ═══════════════════════════════════════════════════════════════════════════════
 */

import { execSync, spawn } from 'child_process';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { createInterface } from 'readline';

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

// ═══════════════════════════════════════════════════════════════════════════════
// CONFIG
// ═══════════════════════════════════════════════════════════════════════════════

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

// ═══════════════════════════════════════════════════════════════════════════════
// UTILS
// ═══════════════════════════════════════════════════════════════════════════════

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

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

async function promptYesNo(question) {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  return new Promise((resolve) => {
    rl.question(`${question} (y/N): `, (answer) => {
      rl.close();
      resolve(answer.toLowerCase().startsWith('y'));
    });
  });
}

async function runCommandAsync(cmd, description) {
  return new Promise((resolve, reject) => {
    console.log(`🔧 ${description}`);
    console.log(`   $ ${cmd}`);

    const child = spawn(cmd, { shell: true, stdio: 'inherit' });

    child.on('close', (code) => {
      if (code === 0) {
        console.log(`✅ ${description} terminé`);
        resolve(true);
      } else {
        console.error(`❌ Erreur (code ${code})`);
        reject(new Error(`Command failed with code ${code}`));
      }
    });

    child.on('error', (err) => {
      console.error('❌ Erreur:', err.message);
      reject(err);
    });
  });
}

// ═══════════════════════════════════════════════════════════════════════════════
// INSTALLATION STEPS
// ═══════════════════════════════════════════════════════════════════════════════

async function checkDocker() {
  logSection('VÉRIFICATION DOCKER');

  const version = runCommand('docker --version');
  if (!version) {
    console.log('❌ Docker non trouvé');
    console.log('');
    console.log('📥 Installation Docker requise:');

    const platform = process.platform;
    if (platform === 'win32') {
      console.log('   Windows: https://www.docker.com/products/docker-desktop/');
    } else if (platform === 'darwin') {
      console.log('   macOS: https://www.docker.com/products/docker-desktop/');
    } else {
      console.log('   Linux: https://docs.docker.com/engine/install/');
    }

    const answer = await promptYesNo('Voulez-vous ouvrir le site de téléchargement ?');
    if (answer) {
      const url = 'https://www.docker.com/products/docker-desktop/';
      const openCmd = process.platform === 'win32' ? 'start' :
                      process.platform === 'darwin' ? 'open' : 'xdg-open';
      runCommand(`${openCmd} ${url}`, { stdio: 'ignore' });
      console.log('✅ Navigateur ouvert. Installez Docker, puis relancez: npm install -g overmind-mcp');
    }

    return false;
  }

  console.log('✅ Docker détecté:', version.trim());
  return true;
}

async function setupInfrastructure() {
  logSection('TÉLÉCHARGEMENT INFRASTRUCTURE');

  mkdirSync(INSTALL_DIR, { recursive: true });

  console.log('📥 Téléchargement docker-compose.yml...');

  const composeUrl = 'https://raw.githubusercontent.com/DeamonDev888/overmind-mcp/main/docker-compose.yml';
  const exportersUrl = 'https://raw.githubusercontent.com/DeamonDev888/overmind-mcp/main/docker-compose.exporters.yml';

  try {
    const composeData = runCommand(`curl -sL --max-time 30 ${composeUrl}`);
    if (composeData) {
      writeFileSync(join(INSTALL_DIR, 'docker-compose.yml'), composeData);
      console.log('✅ docker-compose.yml téléchargé');
    }

    const exportersData = runCommand(`curl -sL --max-time 30 ${exportersUrl}`);
    if (exportersData) {
      writeFileSync(join(INSTALL_DIR, 'docker-compose.exporters.yml'), exportersData);
      console.log('✅ docker-compose.exporters.yml téléchargé');
    }

    return true;
  } catch (error) {
    console.error('❌ Erreur téléchargement:', error.message);
    return false;
  }
}

async function startInfrastructure() {
  logSection('DÉMARRAGE INFRASTRUCTURE DOCKER');

  const composeFile = join(INSTALL_DIR, 'docker-compose.yml');

  if (!existsSync(composeFile)) {
    console.log('⚠️  docker-compose.yml non trouvé. Installation infrastructure skippée.');
    return false;
  }

  try {
    console.log('🚀 Démarrage des services...');
    await runCommandAsync(
      `cd "${INSTALL_DIR}" && docker-compose -f docker-compose.yml up -d`,
      'Démarrage infrastructure'
    );

    console.log('');
    console.log('⏳ Attente démarrage des services (15s)...');
    await new Promise(resolve => setTimeout(resolve, 15000));

    return true;
  } catch (error) {
    console.error('❌ Erreur démarrage:', error.message);
    return false;
  }
}

async function validateServices() {
  logSection('VALIDATION DES SERVICES');

  console.log('🔍 Vérification des containers...');
  console.log('');

  const services = [
    { name: 'PostgreSQL', filter: 'overmind-postgres-pgvector', check: 'pg_isready' },
  ];

  let allRunning = true;

  for (const service of services) {
    const containerName = runCommand(
      `docker ps --filter "name=${service.filter}" --format "{{.Names}}"`,
      { stdio: 'pipe' }
    );

    if (containerName) {
      const name = containerName.trim();
      console.log(`✅ ${service.name}: ${name}`);
    } else {
      console.log(`❌ ${service.name}: Non trouvé`);
      allRunning = false;
    }
  }

  return allRunning;
}

async function createEnvConfig() {
  const envFile = join(INSTALL_DIR, '.env');

  if (!existsSync(envFile)) {
    logSection('CRÉATION CONFIGURATION');

    const envContent = `# OverMind-MCP Environment Configuration
# Généré automatiquement par npm install

# PostgreSQL
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=overmind_temp_password_change_me
POSTGRES_DB=overmind

# OpenTelemetry (optionnel)
OTEL_ENABLED=false

# Workspace
OVERMIND_WORKSPACE=${INSTALL_DIR}
`;

    writeFileSync(envFile, envContent);
    console.log('✅ Configuration créée:', envFile);
  }
}

function showSummary() {
  console.log('\n╔══════════════════════════════════════════════════════════════════╗');
  console.log('║              ✅ INSTALLATION TERMINÉE !                            ║');
  console.log('╚══════════════════════════════════════════════════════════════════╝');
  console.log('');
  console.log('📋 SERVICES DISPONIBLES:');
  console.log('');
  console.log('┌─────────────────────────────────────────────────────────────────┐');
  console.log('│ Ouvrez Docker Desktop pour voir tous les containers             │');
  console.log('│                                                                 │');
  console.log('│ URLs utiles:                                                   │');
  console.log('│   • Prometheus: http://localhost:9090                          │');
  console.log('│   • Grafana:      http://localhost:3000 (admin/admin)          │');
  console.log('│   • Jaeger:       http://localhost:16686                         │');
  console.log('│   • RabbitMQ:    http://localhost:15672 (guest/guest)         │');
  console.log('│   • Temporal:     http://localhost:8233                         │');
  console.log('└─────────────────────────────────────────────────────────────────┘');
  console.log('');
  console.log('📚 DOCUMENTATION:');
  console.log('   • https://github.com/DeamonDev888/overmind-mcp');
  console.log('   • https://www.npmjs.com/package/overmind-mcp');
  console.log('');
  console.log('🎉 PROCHAINE ÉTAPE:');
  console.log('   • Créez votre premier agent: overmind create-agent');
  console.log('   • Ou utilisez: overmind-setup --full');
  console.log('');
}

// ═══════════════════════════════════════════════════════════════════════════════
// MAIN
// ═══════════════════════════════════════════════════════════════════════════════

async function main() {
  console.log('╔══════════════════════════════════════════════════════════════════╗');
  console.log('║                                                                ║');
  console.log('║     🚀 OVERMIND-MCP - INSTALLATION AUTOMATIQUE                     ║');
  console.log('║     npm install -g overmind-mcp                                   ║');
  console.log('║                                                                ║');
  console.log('╚══════════════════════════════════════════════════════════════════╝');
  console.log('');

  // Step 1: Check Docker
  const dockerOk = await checkDocker();
  if (!dockerOk) {
    console.log('\n⚠️  Relancez après installation de Docker: npm install -g overmind-mcp');
    return;
  }

  // Step 2: Setup .env
  await createEnvConfig();

  // Step 3: Download docker-compose files
  const downloaded = await setupInfrastructure();
  if (!downloaded) {
    console.log('\n⚠️  Impossible de télécharger l\'infrastructure. Continue en mode minimal.');
    showSummary();
    return;
  }

  // Step 4: Start infrastructure
  const started = await startInfrastructure();
  if (!started) {
    console.log('\n⚠️  Infrastructure non démarrée. Continue en mode minimal.');
    showSummary();
    return;
  }

  // Step 5: Validate services
  await validateServices();

  // Show summary
  showSummary();
}

// Run main
main().catch((error) => {
  console.error('\n❌ ERREUR FATALE:', error.message);
  process.exit(1);
});
