import path from 'path'
import { cpSync, existsSync, mkdirSync } from 'fs'
import { fileURLToPath } from 'url'
import sirv from 'sirv'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

const ASSET_DIRS = ['fonts', 'icons', 'translations', 'embed-icons']
const DEFAULT_MOUNT = '/assets/local'

/**
 * Vite plugin: serve @qiankaka/assets at `/assets/local` in dev/preview,
 * and copy static asset dirs into the build output.
 *
 * @param {import('./vite.js').QiankakaAssetsPluginOptions} [options]
 * @returns {import('vite').Plugin}
 */
export function qiankakaAssetsPlugin(options = {}) {
	const assetsDir = options.assetsDir ?? __dirname
	const mount = options.mount ?? DEFAULT_MOUNT
	const serve = sirv(assetsDir, { dev: true, etag: true, single: false })

	return {
		name: 'qiankaka-assets',
		configureServer(server) {
			server.middlewares.use(mount, serve)
		},
		configurePreviewServer(server) {
			server.middlewares.use(mount, serve)
		},
		configResolved(config) {
			if (config.command !== 'build') return
			if (!existsSync(assetsDir)) {
				throw new Error(
					`@qiankaka/assets not found at ${assetsDir}. ` +
						'Install @qiankaka/assets at the same version as @qiankaka/beem-draw.'
				)
			}
			const outDir = path.isAbsolute(config.build.outDir)
				? config.build.outDir
				: path.join(config.root, config.build.outDir)
			const destRoot = path.join(outDir, mount.replace(/^\//, ''))
			mkdirSync(destRoot, { recursive: true })
			for (const dir of ASSET_DIRS) {
				const src = path.join(assetsDir, dir)
				if (existsSync(src)) {
					cpSync(src, path.join(destRoot, dir), { recursive: true })
				}
			}
		},
	}
}
