#!/usr/bin/env node

/**
 * Script to check file size
 * - Warning when file > 500 lines
 * - Error when file > 1000 lines
 */

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

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

// Files excluded (auto-generated or config)
const EXCLUDED_FILES = [
	'sequelizeService.ts',
	'build-condition.ts',
	'initExport.ts',
	'types.ts',
	'User.ts',
	'init-models.ts',
];

// Folders excluded
const EXCLUDED_FOLDERS = ['database', 'config'];

function countLines(filePath) {
	const content = fs.readFileSync(filePath, 'utf-8');
	return content.split('\n').length;
}

function checkFileSize(directory) {
	const items = fs.readdirSync(directory, { withFileTypes: true });

	for (const item of items) {
		const fullPath = path.join(directory, item.name);
		const relativePath = path.relative(path.join(__dirname, '..'), fullPath);

		if (item.isDirectory()) {
			// Skip excluded folders
			if (EXCLUDED_FOLDERS.includes(item.name)) continue;
			// Skip node_modules, dist, etc.
			if (['node_modules', 'dist', 'coverage', 'templates', 'docs', 'helpers', 'jobs', 'types'].includes(item.name)) {
				continue;
			}
			checkFileSize(fullPath);
		} else if (item.isFile() && item.name.endsWith('.ts')) {
			// Skip excluded files
			if (EXCLUDED_FILES.includes(item.name)) continue;
			// Skip test files
			if (item.name.includes('.test.') || item.name.includes('.spec.')) continue;

			const lineCount = countLines(fullPath);

			if (lineCount > ERROR_THRESHOLD) {
				ERRORS.push(
					`[SIZE] "${relativePath}": ${lineCount} lines (> ${ERROR_THRESHOLD} - needs immediate refactoring)`,
				);
			} else if (lineCount > WARNING_THRESHOLD) {
				WARNINGS.push(
					`[SIZE] "${relativePath}": ${lineCount} lines (> ${WARNING_THRESHOLD} - consider splitting file)`,
				);
			}
		}
	}
}

function main() {
	console.log('📏 Checking file size...\n');
	console.log(`   Threshold: Warning > ${WARNING_THRESHOLD} lines, Error > ${ERROR_THRESHOLD} lines\n`);

	checkFileSize(SRC_DIR);

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

	if (ERRORS.length > 0) {
		console.log('❌ Errors (files too large - mandatory refactoring):');
		ERRORS.forEach((e) => console.log(`  ${e}`));
		console.log(`\n❌ File size check failed: ${ERRORS.length} file(s) too large`);
		console.log('   Please split these files into smaller modules according to SERVICES_REORGANIZATION_PLAN.md');
		process.exit(1);
	}

	if (WARNINGS.length === 0 && ERRORS.length === 0) {
		console.log('✅ File size check passed! All files are within limits.');
	} else if (ERRORS.length === 0) {
		console.log('✅ File size check passed with warnings.');
	}

	process.exit(0);
}

main();
