#!/usr/bin/env node
/**
 * Standalone screenshot capture script using Puppeteer
 * Usage: node capture-approval-screenshots.js <slug> <approvalId> <beforeUrl> <afterUrl>
 */

const puppeteer = require('/home/aria/projects/symph-agency/node_modules/puppeteer');
const fs = require('fs').promises;
const path = require('path');

const SCREENSHOTS_DIR = '/home/aria/projects/symph-agency/public/screenshots';

async function captureScreenshot(url, outputPath) {
  console.log(`[Screenshot] Capturing ${url} -> ${outputPath}`);
  
  await fs.mkdir(path.dirname(outputPath), { recursive: true });
  
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
  });
  
  try {
    const page = await browser.newPage();
    await page.setViewport({ width: 1440, height: 900 });
    
    // Navigate and wait for network to be idle (max 2 connections)
    await page.goto(url, { 
      waitUntil: 'networkidle2',
      timeout: 45000 
    });
    
    // Wait for React hydration by checking for interactive elements
    await page.waitForFunction(() => {
      // Check if main content is rendered (not just skeleton)
      const main = document.querySelector('main');
      if (!main) return false;
      
      // Check if body has computed background color (CSS loaded)
      const body = document.body;
      const bgColor = window.getComputedStyle(body).backgroundColor;
      
      // If bg is transparent or white, CSS hasn't loaded yet
      if (bgColor === 'rgba(0, 0, 0, 0)' || bgColor === 'rgb(255, 255, 255)') {
        return false;
      }
      
      return true;
    }, { timeout: 10000 }).catch(() => {
      console.log('[Screenshot] Warning: Could not verify CSS loaded, continuing anyway');
    });
    
    // Extra wait for fonts and animations
    await new Promise(r => setTimeout(r, 3000));
    
    await page.screenshot({ path: outputPath });
    console.log(`[Screenshot] Success: ${outputPath}`);
    return true;
  } catch (error) {
    console.error(`[Screenshot] Failed: ${error.message}`);
    return false;
  } finally {
    await browser.close();
  }
}

async function main() {
  const [,, slug, approvalId, beforeUrl, afterUrl] = process.argv;
  
  if (!slug || !approvalId || !beforeUrl || !afterUrl) {
    console.error('Usage: capture-approval-screenshots.js <slug> <approvalId> <beforeUrl> <afterUrl>');
    process.exit(1);
  }
  
  const screenshotDir = path.join(SCREENSHOTS_DIR, slug, approvalId);
  const beforePath = path.join(screenshotDir, 'before.png');
  const afterPath = path.join(screenshotDir, 'after.png');
  
  console.log(`[Capture] Starting for ${slug}/${approvalId}`);
  
  // Capture sequentially to avoid resource conflicts
  const beforeOk = await captureScreenshot(beforeUrl, beforePath);
  const afterOk = await captureScreenshot(afterUrl, afterPath);
  
  // Output result as JSON
  console.log(JSON.stringify({
    success: beforeOk && afterOk,
    screenshots: {
      before: `/screenshots/${slug}/${approvalId}/before.png`,
      after: `/screenshots/${slug}/${approvalId}/after.png`
    }
  }));
  
  process.exit(beforeOk && afterOk ? 0 : 1);
}

main().catch(err => {
  console.error('[Capture] Fatal error:', err);
  process.exit(1);
});
