const fs = require('fs').promises;
const path = require('path');
const BackgroundManager = require('./src/lib/backgrounds');

console.log('');
console.log('╔════════════════════════════════════════╗');
console.log('║      CompareKit Setup Wizard           ║');
console.log('╚════════════════════════════════════════╝');
console.log('');

async function setup() {
  console.log('🔧 Setting up CompareKit...\n');

  // 1. Create necessary directories
  console.log('📁 Creating directories...');
  const dirs = [
    'cache/logos',
    'cache/backgrounds',
    'public/assets/backgrounds',
    'generated'
  ];

  for (const dir of dirs) {
    const dirPath = path.join(__dirname, dir);
    await fs.mkdir(dirPath, { recursive: true });
    console.log(`  ✓ ${dir}`);
  }

  // 2. Check for .env file
  console.log('\n🔑 Checking environment configuration...');
  const envPath = path.join(__dirname, '.env');
  const envExamplePath = path.join(__dirname, '.env.example');

  try {
    await fs.access(envPath);
    console.log('  ✓ .env file exists');
  } catch {
    console.log('  ⚠ No .env file found, creating from template...');
    const envExample = await fs.readFile(envExamplePath, 'utf-8');
    await fs.writeFile(envPath, envExample);
    console.log('  ✓ .env file created');
    console.log('  ℹ Please edit .env and add your API keys (optional)');
  }

  // 3. Generate sample backgrounds
  console.log('\n🎨 Generating sample backgrounds...');
  const bgManager = new BackgroundManager();

  try {
    await bgManager.createSampleBackgrounds();
    console.log('  ✓ Sample backgrounds generated');
  } catch (error) {
    console.error('  ✗ Failed to generate backgrounds:', error.message);
  }

  // 4. Test logo fetching
  console.log('\n🎯 Testing logo fetching...');
  const LogoFetcher = require('./src/lib/logos');
  const logoFetcher = new LogoFetcher();

  try {
    console.log('  Fetching test logo (Semrush)...');
    await logoFetcher.fetchLogo('semrush');
    console.log('  ✓ Logo fetching works!');
  } catch (error) {
    console.error('  ⚠ Logo fetching issue:', error.message);
    console.log('  ℹ This is OK - placeholders will be used');
  }

  // 5. Show statistics
  console.log('\n📊 Setup Statistics:');
  const cacheStats = await logoFetcher.getCacheStats();
  console.log(`  • Cached logos: ${cacheStats.count}`);

  const bgFiles = await fs.readdir(path.join(__dirname, 'public/assets/backgrounds'));
  console.log(`  • Background images: ${bgFiles.length}`);

  // 6. Final instructions
  console.log('\n✅ Setup Complete!');
  console.log('\n📝 Next Steps:');
  console.log('  1. Review .env file and add API keys (optional)');
  console.log('  2. Run: npm start');
  console.log('  3. Visit: http://localhost:3000');
  console.log('');
  console.log('💡 Tips:');
  console.log('  • Clearbit logo API works without a key for most requests');
  console.log('  • Add API keys for Brandfetch/Unsplash for better results');
  console.log('  • Run "npm run dev" for development with auto-reload');
  console.log('');
}

setup().catch(error => {
  console.error('\n❌ Setup failed:', error);
  process.exit(1);
});
