#!/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))

// Determine agent type from --agent flag (default: claude)
const args = process.argv.slice(2)
let agentType = 'claude'
const agentIdx = args.indexOf('--agent')
if (agentIdx !== -1 && args[agentIdx + 1]) {
  agentType = args[agentIdx + 1].toLowerCase()
  args.splice(agentIdx, 2) // remove --agent and its value from args
}

const VALID_TYPES = ['claude', 'codex', 'opencode', 'native']
if (!VALID_TYPES.includes(agentType)) {
  console.error(`Unknown agent type: ${agentType}. Use: ${VALID_TYPES.join(', ')}`)
  process.exit(1)
}

// 'native' type uses cortices-daemon.ts, others use <type>-daemon.ts
const daemonName = agentType === 'native' ? 'cortices-daemon' : `${agentType}-daemon`
const bytecode = resolve(__dirname, '..', 'dist', `${daemonName}.cjs`)
const bundled = resolve(__dirname, '..', 'dist', `${daemonName}.mjs`)
const source = resolve(__dirname, '..', `${daemonName}.ts`)

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