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

export interface BuildOptions {
	workflowsDir: string
	outDir: string
}

export async function runBuild(opts: BuildOptions): 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 outDirResolved = path.resolve(projectRoot, opts.outDir)

	const { config, cleanup } = createPreviewConfig({
		appDir,
		workflowsDir,
		staticDir,
		projectRoot,
		packageRoot,
	})

	try {
		await build({
			...config,
			build: {
				...config.build,
				outDir: outDirResolved,
			},
		})

		// Copy rfw-preview static files to output for production serving
		if (fs.existsSync(staticDir)) {
			const destMobileDir = path.join(outDirResolved, 'mobile')
			fs.cpSync(staticDir, destMobileDir, { recursive: true })
			console.log(`Copied rfw-preview static files to ${destMobileDir}`)
		}

		// Copy rfwtxt files to output so the Flutter iframe can fetch them.
		// In dev mode, middleware serves these dynamically. In a static build,
		// they need to be physically present at mobile/workflows/*/mobile/*.rfwtxt
		const rfwtxtFiles = globbySync('*/mobile/*.rfwtxt', { cwd: workflowsDir })
		for (const file of rfwtxtFiles) {
			const src = path.join(workflowsDir, file)
			const dest = path.join(outDirResolved, 'mobile', 'workflows', file)
			fs.mkdirSync(path.dirname(dest), { recursive: true })
			fs.cpSync(src, dest)
		}
		if (rfwtxtFiles.length > 0) {
			console.log(`Copied ${rfwtxtFiles.length} rfwtxt files to mobile/workflows/`)
		}

		console.log(`Preview build complete: ${outDirResolved}`)
	} finally {
		cleanup()
	}
}
