/**
 * Run a command with the MSVC x64 environment, without opening any window.
 *
 *   bun tools/msvc.ts [--cwd <dir>] <command> [args…]
 *   bun tools/msvc.ts --cwd <native-project> cargo build --release
 *
 * vcvars64.bat runs once; its environment is cached in .cache/msvc-env.json.
 * PATH drops msys2, coreutils and Git usr\bin entries, whose `link` and `cmd` shadow link.exe
 * and cmd.exe on Windows. Exit code is the command's.
 */
import { spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'

const VCVARS = process.env.MSVC_VCVARS ?? 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat'
const CMD = path.join(process.env.SystemRoot ?? 'C:/Windows', 'System32/cmd.exe')
const root = path.resolve(import.meta.dir, '..')
const cacheFile = path.join(root, '.cache/msvc-env.json')

function msvcEnv(): Record<string, string> {
  if (existsSync(cacheFile)) return JSON.parse(readFileSync(cacheFile, 'utf8'))
  const r = spawnSync(CMD, ['/d', '/s', '/c', `"call "${VCVARS}" >nul 2>nul && set"`], {
    windowsVerbatimArguments: true, windowsHide: true, encoding: 'utf8',
  })
  if (r.status !== 0) throw new Error(`vcvars64 failed (${r.status}): ${r.stderr}`)
  const env: Record<string, string> = {}
  for (const line of r.stdout.split(/\r?\n/)) {
    const i = line.indexOf('=')
    if (i > 0) env[line.slice(0, i)] = line.slice(i + 1)
  }
  mkdirSync(path.dirname(cacheFile), { recursive: true })
  writeFileSync(cacheFile, JSON.stringify(env, null, 2))
  return env
}

const args = process.argv.slice(2)
let cwd = process.cwd()
if (args[0] === '--cwd') {
  cwd = path.resolve(args[1] ?? '.')
  args.splice(0, 2)
}
if (!args.length) {
  console.error('usage: bun tools/msvc.ts [--cwd <dir>] <command> [args…]')
  process.exit(2)
}

const env = { ...process.env, ...msvcEnv() }
const pathKey = Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'Path'
env[pathKey] = (env[pathKey] ?? '').split(';')
  .filter((p) => !/msys|coreutils|\\git\\usr\\bin/i.test(p))
  .join(';')

const r = spawnSync(args[0]!, args.slice(1), { cwd, env, stdio: 'inherit', windowsHide: true, shell: false })
if (r.error) throw r.error
process.exit(r.status ?? 1)
