#!/usr/bin/env node

import { dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import { existsSync } from 'fs'
import { execFileSync } from 'child_process'

const __dirname = dirname(fileURLToPath(import.meta.url))
const bytecode = resolve(__dirname, '..', 'dist', 'codex-daemon.cjs')  // bytecode loader
const bundled = resolve(__dirname, '..', 'dist', 'codex-daemon.mjs')   // esbuild ESM
const source = resolve(__dirname, '..', 'codex-daemon.ts')             // dev source

try {
  if (existsSync(bytecode)) {
    execFileSync('node', [bytecode, ...process.argv.slice(2)], {
      stdio: 'inherit', env: process.env,
    })
  } else if (existsSync(bundled)) {
    execFileSync('node', [bundled, ...process.argv.slice(2)], {
      stdio: 'inherit', env: process.env,
    })
  } else {
    execFileSync('npx', ['tsx', source, ...process.argv.slice(2)], {
      stdio: 'inherit', env: process.env,
    })
  }
} catch (e) {
  process.exit(e.status || 1)
}
