#!/usr/bin/env node

/**
 * Cody CLI launcher
 *
 * Ensures Bun runtime is available (required for the bundled CLI),
 * then execs the real CLI. Auto-installs Bun if missing.
 *
 * npm i -g @ainative/cody-cli && cody
 */

const { execSync, spawn } = require('child_process')
const { existsSync } = require('fs')
const path = require('path')

const CLI_BUNDLE = path.join(__dirname, '..', 'dist', 'cli.js')
const MIN_BUN_VERSION = '1.2.0'

const IS_WINDOWS = process.platform === 'win32'

function findBun() {
  // HOME on Windows is USERPROFILE; fall back to HOME for Unix
  const home = process.env.USERPROFILE || process.env.HOME || ''
  const candidates = IS_WINDOWS
    ? [
        path.join(home, '.bun', 'bin', 'bun.exe'),
        path.join(home, '.bun', 'bin', 'bun'),
      ]
    : [
        path.join(home, '.bun', 'bin', 'bun'),
        '/usr/local/bin/bun',
        '/opt/homebrew/bin/bun',
      ]

  // Also check PATH using platform-appropriate command
  try {
    const cmd = IS_WINDOWS ? 'where.exe bun' : 'which bun 2>/dev/null'
    const p = execSync(cmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim().split('\n')[0].trim()
    if (p) candidates.unshift(p)
  } catch {}

  for (const c of candidates) {
    if (existsSync(c)) return c
  }
  return null
}

function getBunVersion(bunPath) {
  try {
    return execSync(`${bunPath} --version`, { encoding: 'utf8' }).trim()
  } catch {
    return '0.0.0'
  }
}

function versionGte(a, b) {
  const pa = a.split('.').map(Number)
  const pb = b.split('.').map(Number)
  for (let i = 0; i < 3; i++) {
    if ((pa[i] || 0) > (pb[i] || 0)) return true
    if ((pa[i] || 0) < (pb[i] || 0)) return false
  }
  return true
}

function installBun() {
  console.error('Cody CLI requires Bun >= ' + MIN_BUN_VERSION + '. Installing...')
  try {
    if (IS_WINDOWS) {
      // Windows: use PowerShell installer (Refs #3117)
      execSync('powershell -NoProfile -ExecutionPolicy Bypass -Command "irm bun.sh/install.ps1 | iex"', { stdio: 'inherit' })
    } else {
      execSync('curl -fsSL https://bun.sh/install | bash', { stdio: 'inherit' })
    }
    const bun = findBun()
    if (bun) return bun
  } catch {}
  const installCmd = IS_WINDOWS
    ? 'powershell -NoProfile -ExecutionPolicy Bypass -Command "irm bun.sh/install.ps1 | iex"'
    : 'curl -fsSL https://bun.sh/install | bash'
  console.error('\nFailed to install Bun. Install manually: ' + installCmd)
  process.exit(1)
}

// Find Bun
let bun = findBun()

// Check version — upgrade if too old
if (bun) {
  const version = getBunVersion(bun)
  if (!versionGte(version, MIN_BUN_VERSION)) {
    console.error(`Bun ${version} is too old (need >= ${MIN_BUN_VERSION}). Upgrading...`)
    try {
      execSync(`${bun} upgrade`, { stdio: 'inherit' })
    } catch {
      bun = installBun()
    }
  }
} else {
  bun = installBun()
}

// Run the CLI
const child = spawn(bun, ['run', CLI_BUNDLE, ...process.argv.slice(2)], {
  stdio: 'inherit',
  env: process.env,
})

child.on('exit', (code) => process.exit(code ?? 0))
child.on('error', (err) => {
  console.error(`Failed to start Cody CLI: ${err.message}`)
  process.exit(1)
})
