#!/usr/bin/env node
/**
 * Configuration validation script
 * Validates .env file has required values
 */

const fs = require('fs');
const path = require('path');

const envPath = path.join(__dirname, '..', '.env');

if (!fs.existsSync(envPath)) {
  console.error('❌ .env file not found');
  console.log('💡 Copy env.template to .env and configure:');
  console.log('   cp env.template .env');
  process.exit(1);
}

const envContent = fs.readFileSync(envPath, 'utf8');
const envVars = {};

envContent.split('\n').forEach((line) => {
  const trimmed = line.trim();
  if (trimmed && !trimmed.startsWith('#')) {
    const [key, ...valueParts] = trimmed.split('=');
    if (key) {
      envVars[key.trim()] = valueParts.join('=').trim();
    }
  }
});

const requiredVars = [
  'HTTP_PORT',
  'WS_PORT',
  'BESU_HTTP_URLS',
  'BESU_WS_URLS',
  'CHAIN_ID',
  'WEB3SIGNER_URL',
  'REDIS_HOST',
  'REDIS_PORT',
];

const missingVars = requiredVars.filter((varName) => {
  const value = envVars[varName];
  return !value || value === '' || value.includes('XXX');
});

if (missingVars.length > 0) {
  console.error('❌ Missing or incomplete configuration:');
  missingVars.forEach((varName) => {
    console.error(`   - ${varName}`);
  });
  console.log('\n💡 Please edit .env and set all required values');
  process.exit(1);
}

console.log('✅ Configuration validation passed');
console.log(`   HTTP Port: ${envVars.HTTP_PORT}`);
console.log(`   WS Port: ${envVars.WS_PORT}`);
console.log(`   Chain ID: ${envVars.CHAIN_ID}`);
console.log(`   Besu HTTP: ${envVars.BESU_HTTP_URLS}`);
console.log(`   Redis: ${envVars.REDIS_HOST}:${envVars.REDIS_PORT}`);
