import puppeteer from 'puppeteer-core';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';

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

// Configuration
const OUTPUT_DIR = path.join(__dirname, '..', 'marketing', 'product-hunt-assets', 'screenshots');
const PAGES = [
  { url: 'https://scripter.app/pricing', filename: 'ph-screenshot-01-pricing-1920x1080.png' },
  { url: 'https://scripter.app/features', filename: 'ph-screenshot-02-features-1920x1080.png' },
  { url: 'https://scripter.app/', filename: 'ph-screenshot-03-home-1920x1080.png' },
  { url: 'https://scripter.app/waitlist', filename: 'ph-screenshot-04-waitlist-1920x1080.png' }
];

// Chromium executable path (adjust if needed)
const CHROMIUM_PATH = process.env.CHROMIUM_PATH || '/usr/bin/chromium-browser';

async function captureScreenshots() {
  console.log('🎬 Starting Product Hunt screenshot capture...\n');
  
  // Ensure output directory exists
  if (!fs.existsSync(OUTPUT_DIR)) {
    fs.mkdirSync(OUTPUT_DIR, { recursive: true });
    console.log(`✅ Created output directory: ${OUTPUT_DIR}\n`);
  }

  let browser;
  try {
    // Launch browser
    console.log('🚀 Launching browser...');
    browser = await puppeteer.launch({
      executablePath: CHROMIUM_PATH,
      headless: 'new',
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-gpu'
      ]
    });

    const page = await browser.newPage();
    await page.setViewport({ width: 1920, height: 1080 });

    // Capture each page
    for (const { url, filename } of PAGES) {
      try {
        console.log(`📸 Capturing: ${url}`);
        
        await page.goto(url, { 
          waitUntil: 'networkidle2',
          timeout: 30000 
        });
        
        // Wait for any lazy-loaded content
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        const outputPath = path.join(OUTPUT_DIR, filename);
        await page.screenshot({ 
          path: outputPath, 
          fullPage: true,
          type: 'png'
        });
        
        console.log(`✅ Saved: ${filename}\n`);
      } catch (error) {
        console.error(`❌ Failed to capture ${url}: ${error.message}\n`);
      }
    }

    console.log('🎉 Screenshot capture complete!');
    console.log(`📁 Files saved to: ${OUTPUT_DIR}`);
    
  } catch (error) {
    console.error('💥 Error:', error.message);
    process.exit(1);
  } finally {
    if (browser) {
      await browser.close();
    }
  }
}

// Run the script
captureScreenshots();
