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

const projectsDir = 'd:/Works/2026/multiphp/generated_configs/projects_apache';

if (!fs.existsSync(projectsDir)) {
    console.log('No project configurations found.');
    process.exit(0);
}

const confFiles = fs.readdirSync(projectsDir).filter(f => f.endsWith('.conf'));

for (const file of confFiles) {
    const filePath = path.join(projectsDir, file);
    console.log(`Updating ${filePath}...`);
    let content = fs.readFileSync(filePath, 'utf8');
    
    // Extract HOST and PATH from Alias line
    const aliasRegex = /Alias\s+\/([^\s]+)\s+"([^"]+)"/;
    const match = content.match(aliasRegex);
    
    if (match) {
        const hostname = match[1];
        let filepath = match[2];
        
        // Extract PORT from current SetHandler (if present)
        const portRegex = /proxy:fcgi:\/\/127\.0\.0\.1:(\d+)/;
        const portMatch = content.match(portRegex);
        const port = portMatch ? portMatch[1] : '9001';
        
        // Ensure filepath ends with /
        if (!filepath.endsWith('/')) filepath += '/';
        
        // THE TRICK: URL-encode spaces in the path for ProxyPassMatch
        const encodedPath = filepath.replace(/ /g, '%20');
        
        // Re-construct the file: Keep Alias and Directory, replace PHP logic
        const directoryBlockRegex = /<Directory "[^"]+">[\s\S]*?<\/Directory>/;
        let newContent = content.match(directoryBlockRegex)[0];
        
        // Remove SetHandler from Directory block
        newContent = newContent.replace(/<FilesMatch \.php$>[\s\S]*?<\/FilesMatch>/g, '');
        
        // Start fresh: Alias + Directory + ProxyPassMatch
        const finalContent = `Alias /${hostname} "${filepath}"
${newContent}

# Explicit PHP mapping for ${hostname} (ProxyPassMatch pattern)
ProxyPassMatch "^/${hostname}/(.*\\.php(/.*)?)$" "fcgi://127.0.0.1:${port}/${encodedPath}$1"
`;
        
        fs.writeFileSync(filePath, finalContent, 'utf8');
    }
}

console.log('Done.');
