#!/usr/bin/env bun

/**
 * Nucleus CLI — the single front door to nucleus-core-ts.
 *
 *   nucleus init          scaffold a new project (interactive)
 *   nucleus dev …         run locally (up | down | run)
 *   nucleus add …         extend an existing project (entity | feature | oauth)
 *   nucleus validate      validate config.json against the schema
 *   nucleus doctor        check the local environment (bun, postgres, redis, …)
 *   nucleus generate      generate the Drizzle schema from config.json
 */

import { spawn } from 'node:child_process'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { addCommand } from './lib/commands/add'
import { devCommand } from './lib/commands/dev'
import { doctorCommand } from './lib/commands/doctor'
import { initCommand } from './lib/commands/init'
import { validateCommand } from './lib/commands/validate'
import { banner, c, log } from './lib/ui'

const here = dirname(fileURLToPath(import.meta.url))
const rootDir = join(here, '..')

const argv = process.argv.slice(2)
const firstArg = argv[0] ?? ''
const looksLikeFile =
  firstArg.endsWith('.json') || firstArg.startsWith('./') || firstArg.startsWith('/')
const command = looksLikeFile ? 'generate' : firstArg

async function pkgVersion(): Promise<string> {
  try {
    return (JSON.parse(await Bun.file(join(rootDir, 'package.json')).text()) as { version: string })
      .version
  } catch {
    return '?'
  }
}

function showHelp(version: string) {
  banner(`Nucleus CLI  v${version}`, 'nucleus-core-ts — config-driven backend framework')
  log(`
${c.bold('Usage')}  ${c.cyan('nucleus')} ${c.dim('<command> [options]')}

${c.bold('Create & evolve')}
  ${c.cyan('init')} ${c.dim('[--preset <p>] [-o <dir>] [-y]')}       build a config + scaffold a runnable backend (zero-to-running)
  ${c.cyan('add')} ${c.dim('entity | feature <n> | oauth <p>')}    extend this project's config in place (+ regenerate)
  ${c.cyan('scaffold')}                               full-project scaffold (backend+frontend+k8s+pipelines) from a config.json
  ${c.cyan('generate')} ${c.dim('<config.json> <outDir>')}           generate the Drizzle schema + relations from config
  ${c.cyan('validate')} ${c.dim('[config.json]')}                    validate a config against the JSON-Schema + cross-field rules

${c.bold('Local dev')}
  ${c.cyan('dev')} ${c.dim('[up | down]')}                          run the app; ${c.dim('up')} starts Postgres+Redis, ${c.dim('down')} stops them
  ${c.cyan('doctor')}                                 check the local environment can run a Nucleus project

${c.bold('Maintenance')}
  ${c.cyan('audit:purge-noise')} ${c.dim('[--execute]')}            delete historical low-signal audit_logs rows (dry-run by default)
  ${c.cyan('help')}${c.dim(', ')}${c.cyan('--version')}                        this help / the installed version

${c.dim('init = preset → runnable backend · scaffold (= new) = full project · Aliases: generate = gen, validate = check')}
`)
}

function runScript(scriptRelPath: string, args: string[]): Promise<never> {
  return new Promise<never>(() => {
    const proc = spawn('bun', ['run', join(rootDir, scriptRelPath), ...args], {
      cwd: process.cwd(),
      stdio: 'inherit',
    })
    proc.on('close', (code) => process.exit(code ?? 1))
  })
}

switch (command) {
  case 'init':
    process.exit(await initCommand(argv.slice(1)))
    break

  case 'dev':
    process.exit(await devCommand(argv.slice(1)))
    break

  case 'add':
    process.exit(await addCommand(argv.slice(1)))
    break

  case 'scaffold':
  case 'new': {
    // Full-project scaffold (backend + frontend + k8s + pipelines) from an
    // existing config.json. `init` is the leaner, config-building local-dev path.
    const { scaffold } = await import(join(rootDir, 'infra', 'scripts', 'generate-project.ts'))
    await scaffold(join(rootDir, 'infra'))
    break
  }

  case 'generate':
  case 'gen': {
    const genArgs = looksLikeFile ? argv : argv.slice(1)
    await runScript(join('scripts', 'generate-schema.ts'), genArgs)
    break
  }

  case 'validate':
  case 'check':
    process.exit(await validateCommand(argv.slice(1)))
    break

  case 'doctor':
    process.exit(await doctorCommand())
    break

  case 'audit:purge-noise':
  case 'audit-purge-noise':
    await runScript(join('scripts', 'audit-purge-noise.ts'), argv.slice(1))
    break

  case '--version':
  case '-v':
    log(await pkgVersion())
    break

  case 'help':
  case '--help':
  case '-h':
  case '':
  case undefined:
    showHelp(await pkgVersion())
    break

  default:
    log(`${c.red('Unknown command:')} ${command}\n`)
    showHelp(await pkgVersion())
    process.exit(1)
}
