import path from 'node:path'
import { globbySync } from 'globby'

export interface WorkflowEntry {
	workflow: string
	task: string
	platform: 'web' | 'mobile'
	filePath: string
}

/**
 * Discover all workflow entries (web + mobile) from the workflows directory.
 * Used by the index page to show a grouped list of all available previews.
 */
export function discoverWorkflows(workflowsDir: string): WorkflowEntry[] {
	const entries: WorkflowEntry[] = []

	const webMatches = globbySync('*/web/*/main.tsx', { cwd: workflowsDir })
	for (const match of webMatches) {
		const [workflow, , task] = match.split('/')
		entries.push({
			workflow,
			task,
			platform: 'web',
			filePath: path.join(workflowsDir, match),
		})
	}

	const mobileMatches = globbySync('*/mobile/*.rfwtxt', { cwd: workflowsDir })
	for (const match of mobileMatches) {
		const [workflow, , file] = match.split('/')
		const task = file.replace('.rfwtxt', '')
		entries.push({
			workflow,
			task,
			platform: 'mobile',
			filePath: path.join(workflowsDir, match),
		})
	}

	return entries
}

/**
 * Discover Module Federation exposes from workflow web components.
 * Returns a map of expose name -> absolute file path.
 *
 * Example: { "./001-demo-workflow/verify-item-details": "/abs/path/to/main.tsx" }
 */
export function discoverExposes(workflowsDir: string): Record<string, string> {
	const matches = globbySync('*/web/*/main.tsx', { cwd: workflowsDir })
	const exposes: Record<string, string> = {}

	for (const match of matches) {
		const [workflow, , task] = match.split('/')
		exposes[`./${workflow}/${task}`] = path.join(workflowsDir, match)
	}

	return exposes
}
