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

const generatedDir = path.join('d:/Works/2026/multiphp', 'generated_configs');
const projectsDir = path.join(generatedDir, 'projects_apache');

function fixApacheConfig(filePath) {
    if (!fs.existsSync(filePath)) return;
    console.log(`Updating ${filePath}...`);
    let content = fs.readFileSync(filePath, 'utf8');
    
    // ENSURE trailing slash in SetHandler (opposite of my previous mistake)
    // Match proxy:fcgi://127.0.0.1:PORT and ensure it ends with /
    const newContent = content.replace(/SetHandler "proxy:fcgi:\/\/127\.0\.0\.1:(\d+)(?!\/)"/g, 'SetHandler "proxy:fcgi://127.0.0.1:$1/"');
    
    // Ensure ProxyFCGIBackendType GENERIC is there (it should be in global httpd.conf)
    let finalContent = newContent;
    if (path.basename(filePath) === 'httpd.conf') {
        if (!finalContent.includes('ProxyFCGIBackendType GENERIC')) {
            // Find a good place, maybe after LoadModule
            finalContent = finalContent.replace(/(LoadModule proxy_fcgi_module .+)/, '$1\n\n<IfModule proxy_fcgi_module>\n    ProxyFCGIBackendType GENERIC\n</IfModule>');
        }
    }
    
    fs.writeFileSync(filePath, finalContent, 'utf8');
}

// 1. Global config
fixApacheConfig(path.join(generatedDir, 'httpd.conf'));

// 2. Project configs
if (fs.existsSync(projectsDir)) {
    const projectFiles = fs.readdirSync(projectsDir);
    for (const file of projectFiles) {
        if (file.endsWith('.conf')) {
            fixApacheConfig(path.join(projectsDir, file));
        }
    }
}

console.log('Done.');
