#!/usr/bin/env node
/**
 * Compare Dev and Prod Databases
 * Identifies documents that exist in one but not the other
 */

require('dotenv').config();
const { MongoClient } = require('mongodb');

async function compareDatabases() {
  // Connect to local dev
  console.log('🔌 Connecting to local dev database...');
  const devClient = new MongoClient('mongodb://localhost:27017/tractatus_dev');
  await devClient.connect();
  const devDb = devClient.db('tractatus_dev');
  const devColl = devDb.collection('documents');

  // Connect to local prod (for comparison)
  console.log('🔌 Connecting to local prod database...\n');
  const prodClient = new MongoClient('mongodb://localhost:27017/tractatus_prod');
  await prodClient.connect();
  const prodDb = prodClient.db('tractatus_prod');
  const prodColl = prodDb.collection('documents');

  // Get all documents
  const devDocs = await devColl.find({}).project({ slug: 1, title: 1, visibility: 1 }).sort({ slug: 1 }).toArray();
  const prodDocs = await prodColl.find({}).project({ slug: 1, title: 1, visibility: 1 }).sort({ slug: 1 }).toArray();

  const devSlugs = new Set(devDocs.map(d => d.slug));
  const prodSlugs = new Set(prodDocs.map(d => d.slug));

  const inDevNotProd = devDocs.filter(d => !prodSlugs.has(d.slug));
  const inProdNotDev = prodDocs.filter(d => !devSlugs.has(d.slug));

  console.log('='.repeat(70));
  console.log('DATABASE COMPARISON');
  console.log('='.repeat(70));
  console.log(`Dev total: ${devDocs.length}`);
  console.log(`Prod total: ${prodDocs.length}`);
  console.log(`Difference: ${Math.abs(devDocs.length - prodDocs.length)}`);
  console.log('='.repeat(70));

  if (inDevNotProd.length > 0) {
    console.log(`\n📋 Documents in DEV but NOT in PROD (${inDevNotProd.length}):\n`);
    inDevNotProd.forEach(d => {
      console.log(`  - ${d.slug} [${d.visibility || 'public'}]`);
    });
  }

  if (inProdNotDev.length > 0) {
    console.log(`\n📋 Documents in PROD but NOT in DEV (${inProdNotDev.length}):\n`);
    inProdNotDev.forEach(d => {
      console.log(`  - ${d.slug} [${d.visibility || 'public'}]`);
    });
  }

  if (inDevNotProd.length === 0 && inProdNotDev.length === 0) {
    console.log('\n✅ Dev and Prod have identical document sets!\n');
  }

  await devClient.close();
  await prodClient.close();
  process.exit(0);
}

compareDatabases().catch(error => {
  console.error('❌ Comparison failed:', error);
  process.exit(1);
});
