#!/usr/bin/env bun
import { pathToFileURL } from 'node:url'
import { HERD_COMMAND } from './plans/herd-command'
import { locateKit } from './sync/kit-source'
import { CLI_NAME } from './version/release'

export type CommandModule = { run: (args: string[]) => Promise<number> | number }

export type CommandTable = Record<string, () => Promise<CommandModule>>

export type Resolution =
  | { kind: 'run'; name: string; args: string[] }
  | { kind: 'version' }
  | { kind: 'usage'; exitCode: number; message: string }

/** Commands that stay callable but are not advertised in the usage line. */
const ALIASES = new Set<string>([HERD_COMMAND.alias])

/** One line per command; each entry lazily imports the module that exports its `run`. */
export const COMMANDS: CommandTable = {
  check: () => import('./check/command'),
  config: () => import('./config/command'),
  context: () => import('./context/command'),
  [HERD_COMMAND.name]: () => import('./plans/command'),
  init: () => import('./sync/init-command'),
  [HERD_COMMAND.alias]: () => import('./plans/command'),
  lane: () => import('./lane/command'),
  mermaid: () => import('./mermaid/command'),
  plan: () => import('./plan-contract/command'),
  preview: () => import('./preview/command'),
  secret: () => import('./secrets/command'),
  settled: () => import('./settled/command'),
  sync: () => import('./sync/command'),
  task: () => import('./task-signals/command'),
  update: () => import('./update/command'),
  waiting: () => import('./waiting/command'),
  watch: () => import('./watch/command'),
}

export const resolveCommand = (argv: string[], table: CommandTable): Resolution => {
  const [name, ...args] = argv
  const names = Object.keys(table)
  const advertised = names.filter((entry) => !ALIASES.has(entry))
  const usage = `Usage: ${CLI_NAME} <command> [args]\n       ${CLI_NAME} --version\nCommands: ${advertised.length > 0 ? advertised.join(', ') : '(none yet)'}`
  if (name === '--version' || name === '-v') return { kind: 'version' }
  if (!name || name === '--help' || name === '-h') return { kind: 'usage', exitCode: name ? 0 : 1, message: usage }
  if (!names.includes(name)) return { kind: 'usage', exitCode: 1, message: `Unknown command: ${name}\n${usage}` }
  return { kind: 'run', name, args }
}

const installedVersion = async (): Promise<string> => (await locateKit()).version

export const main = async (
  argv: string[],
  table: CommandTable = COMMANDS,
  readVersion: () => Promise<string> = installedVersion,
): Promise<number> => {
  const resolution = resolveCommand(argv, table)
  if (resolution.kind === 'version') {
    console.log(await readVersion())
    return 0
  }
  if (resolution.kind === 'usage') {
    console.log(resolution.message)
    return resolution.exitCode
  }
  const command = await table[resolution.name]()
  return command.run(resolution.args)
}

if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
  process.exitCode = await main(process.argv.slice(2))
}
