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

function getMaxNesting(filePath) {
    try {
        const content = fs.readFileSync(filePath, 'utf8');
        let maxDepth = 0;
        let currentDepth = 0;

        for (let i = 0; i < content.length; i++) {
            const char = content[i];
            if (char === '{') {
                currentDepth++;
                if (currentDepth > maxDepth) maxDepth = currentDepth;
            } else if (char === '}') {
                currentDepth--;
            }
        }
        return maxDepth;
    } catch (e) {
        return 0;
    }
}

function walk(dir, results = []) {
    const list = fs.readdirSync(dir);
    list.forEach(file => {
        const fullPath = path.join(dir, file);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            if (!['node_modules', 'target', 'dist', '.git', '.gemini', '.brain'].includes(file) && !file.startsWith('.')) {
                walk(fullPath, results);
            }
        } else {
            const ext = path.extname(fullPath);
            if (['.rs', '.js', '.ts', '.html', '.css'].includes(ext)) {
                results.push({
                    path: path.relative(process.cwd(), fullPath),
                    depth: getMaxNesting(fullPath)
                });
            }
        }
    });
    return results;
}

const srcDir = process.cwd();
const files = walk(srcDir);
files.sort((a, b) => b.depth - a.depth);

console.log('--- Source Code Nesting Depth ---');
files.forEach(f => {
    const status = f.depth >= 7 ? '[REFACTOR REQUIRED]' : ' ';
    console.log(`${f.path.padEnd(60)} : ${f.depth.toString().padStart(5)} levels ${status}`);
});
