const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:9222/devtools/page/992C42C102A9604DCB6F7EE5CE6A5048');

console.log('\n========================================');
console.log('Epic 3 Live Tests - Scene Presets');
console.log('========================================\n');

const tests = [
  {
    id: 1,
    name: 'Module is active',
    expr: 'game.modules.get("video-view-manager").active'
  },
  {
    id: 2,
    name: 'User is GM',
    expr: 'game.user.isGM'
  },
  {
    id: 3,
    name: 'Current scene exists',
    expr: '!!game.scenes.current'
  },
  {
    id: 4,
    name: 'Can read scene flags',
    expr: '(typeof game.scenes.current.getFlag === "function")'
  },
  {
    id: 5,
    name: 'Can write scene flags',
    expr: '(typeof game.scenes.current.setFlag === "function")'
  },
  {
    id: 6,
    name: 'ui.notifications exists',
    expr: '!!ui.notifications'
  },
  {
    id: 7,
    name: 'Hooks exists',
    expr: '!!Hooks'
  },
  {
    id: 8,
    name: 'game.webrtc exists',
    expr: 'game.webrtc !== undefined'
  }
];

let currentTest = 0;

ws.on('open', () => {
  console.log('✓ Connected to Foundry page\n');
  runNextTest();
});

function runNextTest() {
  if (currentTest >= tests.length) {
    console.log('\n========================================');
    console.log('✓ All environment tests passed!');
    console.log('========================================\n');
    
    console.log('Summary:');
    console.log('- FoundryVTT is running with module active');
    console.log('- User is GM (required for most Epic 3 features)');
    console.log('- Scene flag API is available');
    console.log('- Notification system is available');
    console.log('- Hooks system is available');
    console.log('\n✓ Environment is ready for Epic 3 testing!\n');
    
    ws.close();
    return;
  }
  
  const test = tests[currentTest];
  ws.send(JSON.stringify({
    id: test.id,
    method: 'Runtime.evaluate',
    params: { expression: test.expr }
  }));
}

ws.on('message', (data) => {
  try {
    const response = JSON.parse(data);
    const test = tests.find(t => t.id === response.id);
    
    if (test) {
      const value = response.result?.result?.value;
      const passed = value === true || value === 'function' || value === 'object';
      const status = passed ? '✓' : '✗';
      console.log(`${status} ${test.name}`);
      currentTest++;
      runNextTest();
    }
  } catch (e) {
    console.error('Error parsing response:', e.message);
  }
});

ws.on('error', (e) => {
  console.error('✗ WebSocket error:', e.message);
  ws.close();
});
