#!/usr/bin/env node

/**
 * Test script for video recording functionality
 * 
 * Usage:
 * - Local development with video: TRADINGVIEW_DEBUG=true TRADINGVIEW_RECORD_VIDEO=true node test-video-recording.js
 * - Local development with GUI: TRADINGVIEW_DEBUG=true node test-video-recording.js
 * - Docker mode: DOCKER_ENV=true node test-video-recording.js
 */

// Test via API endpoint instead of direct import
const https = require('https');
const http = require('http');

async function testVideoRecording() {
  try {
    console.log('🎬 Testing TradingView video recording via API...');
    
    // Check environment
    const isDebugMode = process.env.TRADINGVIEW_DEBUG === 'true';
    const isRecordingEnabled = process.env.TRADINGVIEW_RECORD_VIDEO === 'true';
    const isDocker = process.env.DOCKER_ENV === 'true';
    
    console.log('Environment:');
    console.log(`- Debug mode: ${isDebugMode}`);
    console.log(`- Video recording: ${isRecordingEnabled}`);
    console.log(`- Docker mode: ${isDocker}`);
    
    // Make a POST request to the analyze endpoint
    const postData = JSON.stringify({
      symbol: 'BTCUSD',
      layouts: ['ai'],
      timeframe: '5'
    });

    const options = {
      hostname: 'localhost',
      port: 3000,
      path: '/api/analyze',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    console.log('\n🚀 Making request to /api/analyze endpoint...');
    console.log('This will trigger video recording automatically if enabled.');
    
    const req = http.request(options, (res) => {
      console.log(`Response status: ${res.statusCode}`);
      
      let responseData = '';
      res.on('data', (chunk) => {
        responseData += chunk;
      });
      
      res.on('end', () => {
        try {
          const result = JSON.parse(responseData);
          console.log('✅ Video recording test completed!');
          console.log('Response:', result);
          console.log('\n📁 Check these directories:');
          console.log('- screenshots/ directory for debug screenshots');
          console.log('- videos/ directory for recorded videos');
        } catch (e) {
          console.log('Response:', responseData);
        }
        process.exit(0);
      });
    });

    req.on('error', (e) => {
      console.error('❌ Request failed:', e.message);
      console.log('\n💡 Make sure your Next.js server is running:');
      console.log('   npm run dev');
      process.exit(1);
    });

    req.write(postData);
    req.end();
    
  } catch (error) {
    console.error('❌ Video recording test failed:', error);
    process.exit(1);
  }
}

// Handle process termination
process.on('SIGINT', () => {
  console.log('\n🛑 Stopping video recording test...');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 Stopping video recording test...');
  process.exit(0);
});

testVideoRecording();
