import fs from 'node:fs'
import path from 'node:path'
import { createServer } from 'vite'
import { createPreviewConfig } from '../config/preview-vite.ts'

export interface DevOptions {
	port: number
	workflowsDir: string
}

export async function runDev(opts: DevOptions): Promise<void> {
	const projectRoot = process.cwd()
	const workflowsDir = path.resolve(projectRoot, opts.workflowsDir)
	const packageRoot = path.resolve(import.meta.dirname, '..', '..')
	const appDir = path.resolve(packageRoot, 'app')
	const staticDir = path.resolve(packageRoot, 'static', 'mobile')

	if (!fs.existsSync(workflowsDir)) {
		console.error(`Workflows directory not found: ${workflowsDir}`)
		console.error('Use --workflows to specify the path to your workflows directory.')
		process.exit(1)
	}

	const { config, cleanup } = createPreviewConfig({
		appDir,
		workflowsDir,
		staticDir,
		projectRoot,
		packageRoot,
		port: opts.port,
	})

	const server = await createServer(config)
	await server.listen()

	server.printUrls()
	server.bindCLIShortcuts({ print: true })

	// Cleanup on exit
	const handleExit = () => {
		cleanup()
		server.close()
	}
	process.on('SIGINT', handleExit)
	process.on('SIGTERM', handleExit)
}
