import fs from 'node:fs'
import path from 'node:path'
import { build } from 'vite'
import { createMFConfig } from '../config/mf-vite.ts'

export interface BuildMFOptions {
	workflowsDir: string
	outDir: string
}

/**
 * Read the federation name from the customer's package.json.
 * Falls back to 'customer_workflows' if not found.
 */
function readFederationName(projectRoot: string): string {
	const pkgPath = path.join(projectRoot, 'package.json')
	if (!fs.existsSync(pkgPath)) {
		console.warn('No package.json found in project root, using default federation name.')
		return 'customer_workflows'
	}

	const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
	const name: string = pkg.name ?? 'customer_workflows'

	// Sanitize: MF names must be valid JS identifiers.
	// Replace @scope/name with scope_name, hyphens with underscores.
	return name.replace(/^@/, '').replace(/[/-]/g, '_')
}

export async function runBuildMF(opts: BuildMFOptions): Promise<void> {
	const projectRoot = process.cwd()
	const workflowsDir = path.resolve(projectRoot, opts.workflowsDir)
	const packageRoot = path.resolve(import.meta.dirname, '..', '..')

	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 federationName = readFederationName(projectRoot)
	console.log(`Building Module Federation remote: ${federationName}`)

	const { config, cleanup } = createMFConfig({
		workflowsDir,
		projectRoot,
		packageRoot,
		federationName,
		outDir: opts.outDir,
	})

	try {
		await build(config)
		console.log(`MF remote build complete: ${path.resolve(projectRoot, opts.outDir)}`)
	} finally {
		cleanup()
	}
}
