// bootstrap.cjs — CommonJS, compiled to binary by pkg
// Installs npm deps, links clauth, chains to: clauth install
'use strict';
const { execSync, spawnSync } = require('child_process');
const { join } = require('path');
const ROOT = join(__dirname, '..');

function run(cmd, opts) {
  return spawnSync(cmd, Object.assign({ shell: true, stdio: 'inherit', cwd: ROOT }, opts || {}));
}
function check(cmd) {
  try { execSync(cmd + ' --version', { stdio: 'pipe' }); return true; } catch { return false; }
}

console.log('\n  Installing clauth runtime...\n');

if (!check('git')) {
  console.error('  x git not found. Install from https://git-scm.com');
  process.exit(1);
}
var nodeVer = parseInt(process.version.slice(1));
if (nodeVer < 18) {
  console.error('  x Node.js v18+ required (found ' + process.version + ')');
  console.error('    Install from https://nodejs.org');
  process.exit(1);
}

console.log('  -> Installing dependencies...');
var inst = run('npm install --no-fund --no-audit', { stdio: ['ignore','ignore','pipe'] });
if (inst.status !== 0) { console.error('  x npm install failed'); process.exit(1); }
console.log('  + Dependencies ready');

console.log('  -> Linking clauth command...');
var lnk = run('npm link', { stdio: ['ignore','ignore','pipe'] });
if (lnk.status !== 0) {
  var slnk = run('sudo npm link', { stdio: 'inherit' });
  if (slnk.status !== 0) console.warn('  ! Could not link globally — add ' + ROOT + '/node_modules/.bin to PATH');
}
console.log('  + clauth linked');

// Check if cloudflared is installed
var cfFound = false;
try {
  execSync('cloudflared --version', { stdio: 'ignore' });
  cfFound = true;
} catch {}

if (!cfFound) {
  console.log('\n  cloudflared not found — needed for claude.ai web integration (tunnel).');

  var platform = process.platform;
  var installCmd = null;
  var installLabel = null;

  if (platform === 'win32') {
    try {
      execSync('winget --version', { stdio: 'ignore' });
      installCmd = 'winget install Cloudflare.cloudflared --silent --accept-package-agreements --accept-source-agreements';
      installLabel = 'winget';
    } catch {}
  } else if (platform === 'darwin') {
    try {
      execSync('brew --version', { stdio: 'ignore' });
      installCmd = 'brew install cloudflare/cloudflare/cloudflared';
      installLabel = 'Homebrew';
    } catch {}
  }
  // Linux: no auto-install — falls through to manual instructions

  if (installCmd) {
    process.stdout.write('  Install now via ' + installLabel + '? (y/n): ');
    var answer = (function () {
      try {
        var buf = Buffer.alloc(3);
        var fd = require('fs').openSync('/dev/tty', 'r');
        require('fs').readSync(fd, buf, 0, 3);
        require('fs').closeSync(fd);
        return buf.toString().trim().toLowerCase();
      } catch {
        try {
          var result = require('child_process').spawnSync(
            'powershell',
            ['-Command', "$k = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown'); $k.Character"],
            { encoding: 'utf8' }
          );
          return (result.stdout || '').trim().toLowerCase();
        } catch { return 'n'; }
      }
    })();

    if (answer === 'y') {
      console.log('  Installing cloudflared via ' + installLabel + '...');
      try {
        execSync(installCmd, { stdio: 'inherit' });
        console.log('  + cloudflared installed.');
      } catch (e) {
        console.log('  x Auto-install failed. Install manually:');
        console.log('    https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/');
      }
    } else {
      console.log('  Skipped. Install later and run: clauth tunnel setup');
    }
  } else {
    console.log('  Install manually:');
    if (platform === 'win32') {
      console.log('    winget install Cloudflare.cloudflared');
      console.log('    or: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/');
    } else if (platform === 'darwin') {
      console.log('    brew install cloudflare/cloudflare/cloudflared');
      console.log('    or: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/');
    } else {
      console.log('    https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/');
    }
    console.log('  Then run: clauth tunnel setup');
  }
  console.log('');
}

console.log('\n  -> Launching clauth install...\n');
var r = run('clauth install');
process.exit(r.status || 0);
