#!/usr/bin/env node

/**
 * Standalone event scraper script
 * Can be run manually or via cron job
 * 
 * Usage:
 *   node scripts/run-scraper.js
 *   node scripts/run-scraper.js --init  (to initialize scraper organization)
 */

import { runEventScraper, initializeScraperOrganization } from '../src/lib/eventScraper.js';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { config } from 'dotenv';

// Get the directory of this script
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Load environment variables from the project root
config({ path: join(__dirname, '..', '.env') });
config({ path: join(__dirname, '..', '.env.local') });

async function main() {
  const args = process.argv.slice(2);
  const shouldInit = args.includes('--init');
  
  console.log('🚀 Black Canyon Tickets Event Scraper');
  console.log('======================================');
  
  try {
    if (shouldInit) {
      console.log('🔧 Initializing scraper organization...');
      const initialized = await initializeScraperOrganization();
      
      if (initialized) {
        console.log('✅ Scraper organization initialized successfully');
      } else {
        console.error('❌ Failed to initialize scraper organization');
        process.exit(1);
      }
    }
    
    console.log('🔍 Running event scraper...');
    const result = await runEventScraper();
    
    if (result.success) {
      console.log('✅', result.message);
      
      if (result.newEvent) {
        console.log('📅 New Featured Event Added:');
        console.log(`   Title: ${result.newEvent.title}`);
        console.log(`   Venue: ${result.newEvent.venue}`);
        console.log(`   Category: ${result.newEvent.category}`);
        console.log(`   Start Time: ${result.newEvent.startTime}`);
        
        if (result.newEvent.imageUrl) {
          console.log(`   Image: ${result.newEvent.imageUrl}`);
        }
      }
    } else {
      console.error('❌', result.message);
      process.exit(1);
    }
    
  } catch (error) {
    console.error('💥 Scraper script failed:', error);
    process.exit(1);
  }
}

// Handle uncaught errors
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  process.exit(1);
});

process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  process.exit(1);
});

// Run the script
main();