/**
 * 可选：手动对支付宝产物再跑一遍降级。
 * 日常「运行/发行到支付宝」会由 vite.config.ts 的 alipayEsCompatPlugin 自动处理。
 *
 * 用法：node scripts/alipay-es-compat.js [dir...]
 */
const fs = require('fs');
const path = require('path');

function resolveTransformSync() {
	try {
		return require('esbuild').transformSync;
	} catch (error) {
		try {
			const vitePath = require.resolve('vite');
			const esbuildPath = require.resolve('esbuild', { paths: [path.dirname(vitePath)] });
			return require(esbuildPath).transformSync;
		} catch (inner) {
			throw new Error('找不到 esbuild，请先通过 vite/uni 运行支付宝构建，或安装 esbuild');
		}
	}
}

const transformSync = resolveTransformSync();

const TRANSFORM_OPTIONS = {
	loader: 'js',
	target: 'es2015',
	sourcemap: false,
	supported: {
		arrow: false,
		'template-literal': false,
		'optional-chain': false,
		'nullish-coalescing': false,
		'optional-catch-binding': false,
		'object-rest-spread': false,
		'class-field': false
	}
};

function walkJsFiles(dir, files = []) {
	if (!fs.existsSync(dir)) return files;
	for (const name of fs.readdirSync(dir)) {
		const fullPath = path.join(dir, name);
		if (fs.statSync(fullPath).isDirectory()) {
			walkJsFiles(fullPath, files);
		} else if (name.endsWith('.js')) {
			files.push(fullPath);
		}
	}
	return files;
}

function needsTransform(source) {
	return (
		source.includes('=>') ||
		source.includes('`') ||
		source.includes('?.') ||
		source.includes('??') ||
		/catch\s*\{/.test(source)
	);
}

function transformFile(filePath) {
	const source = fs.readFileSync(filePath, 'utf8');
	if (!needsTransform(source)) return false;
	const result = transformSync(source, TRANSFORM_OPTIONS);
	if (!result.code || result.code === source) return false;
	fs.writeFileSync(filePath, result.code, 'utf8');
	return true;
}

function run(roots) {
	let changed = 0;
	for (const root of roots) {
		const abs = path.resolve(__dirname, '..', root);
		for (const file of walkJsFiles(abs)) {
			try {
				if (transformFile(file)) changed += 1;
			} catch (error) {
				console.warn('[alipay-es-compat] skip', file, error && error.message);
			}
		}
	}
	console.log(`[alipay-es-compat] transformed ${changed} file(s)`);
}

const cliRoots = process.argv.slice(2);
run(
	cliRoots.length
		? cliRoots
		: ['unpackage/dist/dev/mp-alipay', 'unpackage/dist/build/mp-alipay']
);
