#!/usr/bin/env bun

/**
 * Nucleus CLI — unified entry point for all nucleus-core-ts commands.
 *
 * Usage:
 *   npx nucleus-core-ts scaffold    — Interactive project scaffolding
 *   npx nucleus-core-ts generate    — Generate schema from config.json
 *   npx nucleus-core-ts help        — Show available commands
 */

import { spawn } from 'node:child_process'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const BOLD = '\x1b[1m'
const CYAN = '\x1b[36m'
const DIM = '\x1b[2m'
const RED = '\x1b[31m'
const RESET = '\x1b[0m'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const rootDir = join(__dirname, '..')

const firstArg = process.argv[2] ?? ''
const looksLikeFile =
  firstArg.endsWith('.json') || firstArg.startsWith('./') || firstArg.startsWith('/')
const command = looksLikeFile ? 'generate' : firstArg

function showHelp() {
  console.log(`
${CYAN}${BOLD}Nucleus CLI${RESET} ${DIM}(nucleus-core-ts)${RESET}

${BOLD}Usage:${RESET}
  npx nucleus-core-ts ${CYAN}<command>${RESET}

${BOLD}Commands:${RESET}
  ${CYAN}scaffold${RESET}            Interactive project scaffolding (API + frontend + k8s + pipelines)
  ${CYAN}generate${RESET}            Generate Drizzle schema from config.json
  ${CYAN}audit:purge-noise${RESET}   Delete historical low-signal audit_logs rows (dry-run by default)
  ${CYAN}help${RESET}                Show this help message

${BOLD}Examples:${RESET}
  ${DIM}npx nucleus-core-ts scaffold${RESET}
  ${DIM}npx nucleus-core-ts generate src/config.json src/drizzle${RESET}
  ${DIM}npx nucleus-core-ts audit:purge-noise            # dry run, all schemas${RESET}
  ${DIM}npx nucleus-core-ts audit:purge-noise --execute  # actually delete${RESET}
`)
}

async function runScript(scriptRelPath: string, args: string[]) {
  return new Promise<void>(() => {
    const proc = spawn('bun', ['run', join(rootDir, scriptRelPath), ...args], {
      cwd: process.cwd(),
      stdio: 'inherit',
    })
    proc.on('close', (code) => {
      process.exit(code ?? 1)
    })
  })
}

async function runGenerate(args: string[]) {
  return new Promise<void>(() => {
    const proc = spawn('bun', ['run', join(rootDir, 'scripts', 'generate-schema.ts'), ...args], {
      cwd: process.cwd(),
      stdio: 'inherit',
    })
    proc.on('close', (code) => {
      process.exit(code ?? 1)
    })
  })
}

switch (command) {
  case 'scaffold':
  case 'init':
  case 'new': {
    const { scaffold } = await import(join(rootDir, 'infra', 'scripts', 'generate-project.ts'))
    const infraDir = join(rootDir, 'infra')
    await scaffold(infraDir)
    break
  }

  case 'generate':
  case 'gen': {
    const genArgs = looksLikeFile ? process.argv.slice(2) : process.argv.slice(3)
    await runGenerate(genArgs)
    break
  }

  case 'audit:purge-noise':
  case 'audit-purge-noise': {
    await runScript(join('scripts', 'audit-purge-noise.ts'), process.argv.slice(3))
    break
  }

  case 'help':
  case '--help':
  case '-h':
  case undefined:
    showHelp()
    break

  default:
    console.error(`${RED}Unknown command: ${command}${RESET}`)
    showHelp()
    process.exit(1)
}
