const https = require('https');
const fs = require('fs');

// Step 1: Get GitHub device code
const postData = 'client_id=Iv1.1234567890abcdef&scope=read:user';

const options = {
  hostname: 'github.com',
  path: '/login/device/code',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json',
    'User-Agent': 'OpenClaw/1.0',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = https.request(options, (res) => {
  let data = '';
  res.on('data', chunk => data += chunk);
  res.on('end', () => {
    console.log('Status:', res.statusCode);
    try {
      const json = JSON.parse(data);
      console.log('Response:', JSON.stringify(json));
      
      if (json.verification_uri && json.user_code) {
        // Step 2: Generate QR code for the verification URL
        const qrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' + encodeURIComponent(json.verification_uri);
        
        https.get(qrUrl, (qrRes) => {
          const chunks = [];
          qrRes.on('data', c => chunks.push(c));
          qrRes.on('end', () => {
            const buf = Buffer.concat(chunks);
            fs.writeFileSync('/home/node/.openclaw/workspace/assets/github-login-qr.png', buf);
            console.log('QR saved:', buf.length, 'bytes');
            console.log('User code:', json.user_code);
            console.log('Verification URL:', json.verification_uri);
          });
        }).on('error', e => console.error('QR fetch error:', e.message));
      }
    } catch(e) {
      console.error('Parse error:', e.message, data);
    }
  });
});

req.on('error', err => console.error('Request error:', err.message));
req.write(postData);
req.end();