#!/usr/bin/env node

/**
 * Script to detect empty folders
 * According to SERVICES_REORGANIZATION_PLAN.md, there should be no empty folders
 */

const fs = require('fs');
const path = require('path');

const SRC_DIR = path.join(__dirname, '..', 'src');
const WARNINGS = [];
const ERRORS = [];

// Folders allowed to be empty (temporarily during refactoring)
const ALLOWED_EMPTY_FOLDERS = [
	// Currently no folders are allowed to be empty
];

// Folders to be checked specially (according to convention)
const IMPORTANT_FOLDERS = ['services', 'models', 'providers', 'controllers', 'middlewares', 'utils'];

function isAllowedEmpty(relativePath) {
	return ALLOWED_EMPTY_FOLDERS.some((allowed) => relativePath.includes(allowed));
}

function isImportantFolder(folderName) {
	return IMPORTANT_FOLDERS.includes(folderName);
}

function getAllFiles(dirPath, arrayOfFiles = []) {
	const files = fs.readdirSync(dirPath, { withFileTypes: true });

	for (const file of files) {
		if (file.isDirectory()) {
			arrayOfFiles = getAllFiles(path.join(dirPath, file.name), arrayOfFiles);
		} else {
			arrayOfFiles.push(path.join(dirPath, file.name));
		}
	}

	return arrayOfFiles;
}

function checkEmptyFolders(directory, parentPath = '') {
	const items = fs.readdirSync(directory, { withFileTypes: true });
	const relativePath = path.relative(path.join(__dirname, '..'), directory);

	// Filter out folders
	const folders = items.filter((item) => item.isDirectory());

	for (const folder of folders) {
		const fullPath = path.join(directory, folder.name);
		const folderRelativePath = path.relative(path.join(__dirname, '..'), fullPath);

		// Skip node_modules, dist, coverage
		if (['node_modules', 'dist', 'coverage', '.git'].includes(folder.name)) continue;

		// Check if folder is empty (no files recursively)
		const files = getAllFiles(fullPath);
		const hasFiles = files.length > 0;

		if (!hasFiles) {
			if (isAllowedEmpty(folderRelativePath)) {
				WARNINGS.push(`[EMPTY] "${folderRelativePath}" is an empty folder (allowed temporarily)`);
			} else {
				const isImportant = isImportantFolder(folder.name) || isImportantFolder(path.basename(parentPath || directory));
				if (isImportant) {
					ERRORS.push(
						`[EMPTY] "${folderRelativePath}" is an empty folder in ${path.basename(parentPath || directory)}/ - needs to be deleted or have files added`,
					);
				} else {
					WARNINGS.push(`[EMPTY] "${folderRelativePath}" is an empty folder - consider deleting`);
				}
			}
		}

		// Recursively check subdirectories
		checkEmptyFolders(fullPath, directory);
	}
}

function main() {
	console.log('📁 Checking empty folders...\n');

	checkEmptyFolders(SRC_DIR);

	// Report results
	if (WARNINGS.length > 0) {
		console.log('⚠️  Warnings (empty folders - consider deleting):');
		WARNINGS.forEach((w) => console.log(`  ${w}`));
		console.log();
	}

	if (ERRORS.length > 0) {
		console.log('❌ Errors (empty folders must be addressed):');
		ERRORS.forEach((e) => console.log(`  ${e}`));
		console.log(`\n❌ Empty folder check failed: ${ERRORS.length} empty folder(s)`);
		console.log('   Please delete empty folders or add files to them.');
		process.exit(1);
	}

	if (WARNINGS.length === 0 && ERRORS.length === 0) {
		console.log('✅ Empty folder check passed! No empty folders detected.');
	} else if (ERRORS.length === 0) {
		console.log('✅ Empty folder check passed with warnings.');
	}

	process.exit(0);
}

main();
