/*
 * This script generates an index file for each asset folder specified in `assetFolders`.
 * The index file will export all assets in the folder as an object.
 *
 * Usage:
 *   1. Add the names of your asset folders to the `assetFolders` array.
 *   2. Run `pnpm assets gen` to generate the index files.
 *
 * The generated index files will have the name `index.ts` and will be located in the root of each asset folder.
 */
import fs from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import prettier from 'prettier';

const assetFolders = ['icons', 'images', 'videos'];

const lazyAssetFolders = ['svgs/brands', 'svgs/ext/Extras', 'svgs/ext/Code'];

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

prettier.resolveConfig(join(__dirname, '..', '..', '..', '.prettierrc.js')).then((options) =>
	Promise.all(
		[
			...assetFolders.map((e) => /** @type {const} */ ([e, false])),
			...lazyAssetFolders.map((e) => /** @type {const} */ ([e, true]))
		].map(async ([folder, lazy]) => {
			const indexFilePath = join(__dirname, '..', folder, 'index.ts');
			const assetsFolderPath = join(__dirname, '..', folder);

			if (
				await fs.access(indexFilePath).then(
					() => true,
					() => false
				)
			) {
				// Delete the index file if it already exists.
				await fs.unlink(indexFilePath);
			}

			const fileNames = await fs.readdir(assetsFolderPath);

			// Generate the import statements for each asset.
			const assetImports = fileNames
				.filter((fileName) => fileName !== 'index.ts' && !/(^|\/)\.[^\/\.]/g.test(fileName))
				.map((fileName) => {
					const variableName = fileName.split('.')[0].replace(/-/g, '');
					if (folder.startsWith('svgs')) {
						if (lazy)
							return `const ${variableName} = React.lazy(async () => ({ default: (await import('./${fileName}')).ReactComponent }));`;

						return `import { ReactComponent as ${variableName} } from './${fileName}';`;
					}
					return `import ${variableName} from './${fileName}';`;
				})
				.join('\n');

			// Generate the export statements for each asset.
			const assetExports = fileNames
				.filter((fileName) => fileName !== 'index.ts' && !/(^|\/)\.[^\/\.]/g.test(fileName))
				.map((fileName) => `${fileName.split('.')[0].replace(/-/g, '')}`)
				.join(',\n');

			// Generate the index file content.
			const indexFileContent = await prettier.format(
				`
				/*
				 * This file was automatically generated by a script.
				 * To regenerate this file, run: pnpm assets gen
				 */

				${lazy ? `import React from 'react';` : ''}

				${assetImports}

				export {
					${assetExports}
				};`,
				{ ...options, parser: 'typescript' }
			);

			// Write the index file.
			await fs.writeFile(indexFilePath, indexFileContent);
		})
	)
);
