// Direct browserless REST API - navigate and screenshot
const http = require('http');
const fs = require('fs');

async function request(method, path, body, parseJson = true) {
  return new Promise((resolve, reject) => {
    const postData = body ? JSON.stringify(body) : undefined;
    const headers = { 'Content-Type': 'application/json' };
    if (postData) headers['Content-Length'] = Buffer.byteLength(postData);
    const req = http.request({ hostname: 'browserless', port: 3000, path, method, headers }, (res) => {
      let data = '';
      res.on('data', c => data += c);
      res.on('end', () => {
        if (parseJson && res.statusCode >= 200 && res.statusCode < 300) {
          try { resolve(JSON.parse(data)); } catch(e) { resolve(data); }
        } else {
          resolve({ status: res.statusCode, body: data });
        }
      });
    });
    req.on('error', reject);
    if (postData) req.write(postData);
    req.end();
  });
}

async function main() {
  const url = process.argv[2] || 'https://github.com/login/device';
  const outFile = process.argv[3] || '/home/node/.openclaw/workspace/assets/browserless-ss.png';
  
  console.log('Creating session...');
  const session = await request('POST', '/session', { url, headless: true });
  console.log('Session response:', Object.keys(session));
  
  if (session.sessionId) {
    const id = session.sessionId;
    console.log('Session ID:', id);
    
    // Take screenshot via REST
    const ssReq = await request('GET', `/screenshot/${id}`, null);
    console.log('Screenshot result type:', typeof ssReq, ssReq && ssReq.statusCode);
    console.log('Screenshot result keys:', ssReq && Object.keys(ssReq));
    
    // Or use the debug protocol
    const debugUrl = `/debug/${id}`;
    const debugReq = await request('GET', debugUrl, null);
    console.log('Debug response:', typeof debugReq);
    
    await request('DELETE', `/session/${id}`, null);
  }
  
  // Try direct screenshot
  console.log('\nTrying direct /screenshot...');
  const r2 = await request('POST', '/screenshot', { url, type: 'png' });
  if (r2.image) {
    const buf = Buffer.from(r2.image, 'base64');
    fs.writeFileSync(outFile, buf);
    console.log('Direct screenshot:', buf.length, 'bytes');
  } else {
    console.log('Direct screenshot response:', JSON.stringify(r2).substring(0, 300));
  }
}

main().catch(e => { console.error('Error:', e.message); process.exit(1); });
