#!/usr/bin/env node
'use strict';

const { spawnSync } = require('child_process');
const os = require('os');

const args = process.argv.slice(2);
const isWin = os.platform() === 'win32';

// --- helpers ---

function run(cmd, cmdArgs, opts) {
  return spawnSync(cmd, cmdArgs, { stdio: 'inherit', shell: isWin, ...opts });
}

function hasCmd(cmd) {
  const r = spawnSync(isWin ? 'where' : 'which', [cmd], { stdio: 'pipe', shell: isWin });
  return r.status === 0;
}

function fail(msg) {
  process.stderr.write(msg + '\n');
  process.exit(1);
}

// --- main ---

// 1. Already installed? Forward directly.
if (hasCmd('index1')) {
  const r = run('index1', args);
  process.exit(r.status || 0);
}

// 2. Not installed. Try auto-install.
process.stderr.write('index1 未找到，尝试自动安装...\n');

if (hasCmd('pipx')) {
  process.stderr.write('→ pipx install index1\n');
  const install = run('pipx', ['install', 'index1']);
  if (install.status !== 0) {
    fail('❌ pipx install 失败。请手动运行: pipx install index1');
  }
} else if (hasCmd('pip3')) {
  process.stderr.write('→ pip3 install index1\n');
  const install = run('pip3', ['install', 'index1']);
  if (install.status !== 0) {
    fail('❌ pip3 install 失败。请手动运行: pip3 install index1');
  }
} else if (hasCmd('pip')) {
  process.stderr.write('→ pip install index1\n');
  const install = run('pip', ['install', 'index1']);
  if (install.status !== 0) {
    fail('❌ pip install 失败。请手动运行: pip install index1');
  }
} else {
  fail(
    '❌ 未找到 pipx 或 pip。请先安装 Python:\n' +
    '   macOS:   brew install python\n' +
    '   Ubuntu:  sudo apt install python3-pip\n' +
    '   Windows: https://python.org/downloads\n\n' +
    '   然后运行: pipx install index1'
  );
}

// 3. Run the command after installation.
if (hasCmd('index1')) {
  const r = run('index1', args);
  process.exit(r.status || 0);
} else {
  fail(
    '❌ 安装完成但 index1 不在 PATH 中。\n' +
    '   尝试: pipx ensurepath && source ~/.bashrc\n' +
    '   然后重新运行命令。'
  );
}
