#!/usr/bin/env bun

import { parseArgs } from 'node:util'

const { values, positionals } = parseArgs({
	args: process.argv.slice(2),
	options: {
		port: { type: 'string', default: '4173' },
		workflows: { type: 'string', default: './workflows' },
		outdir: { type: 'string' },
		help: { type: 'boolean', short: 'h' },
	},
	allowPositionals: true,
})

const command = positionals[0] ?? 'dev'
const workflowsDir = values.workflows ?? './workflows'

if (values.help) {
	console.log(`
Usage: workflow-preview <command> [options]

Commands:
  dev        Start preview dev server with HMR (default)
  build      Build static preview site
  build:mf   Build Module Federation remote for production

Options:
  --port <number>        Dev server port (default: 4173)
  --workflows <path>     Path to workflows directory (default: ./workflows)
  --outdir <path>        Output directory (default: dist/web or dist/mf)
  -h, --help             Show this help message
`)
	process.exit(0)
}

switch (command) {
	case 'dev': {
		const { runDev } = await import('../src/commands/dev.ts')
		await runDev({
			port: Number(values.port),
			workflowsDir,
		})
		break
	}

	case 'build': {
		const { runBuild } = await import('../src/commands/build.ts')
		await runBuild({
			workflowsDir,
			outDir: values.outdir ?? 'dist/web',
		})
		break
	}

	case 'build:mf': {
		const { runBuildMF } = await import('../src/commands/build-mf.ts')
		await runBuildMF({
			workflowsDir,
			outDir: values.outdir ?? 'dist/mf',
		})
		break
	}

	default:
		console.error(`Unknown command: ${command}`)
		console.error('Run "workflow-preview --help" for usage information.')
		process.exit(1)
}
