#!/usr/bin/env node

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

/**
 * Recursively find all HTML files in a directory
 */
function findHtmlFiles(dir, fileList = []) {
    const files = fs.readdirSync(dir);
    
    for (const file of files) {
        const filePath = path.join(dir, file);
        const stat = fs.statSync(filePath);
        
        if (stat.isDirectory()) {
            // Skip node_modules and hidden directories
            if (file !== 'node_modules' && !file.startsWith('.')) {
                findHtmlFiles(filePath, fileList);
            }
        } else if (file.endsWith('.html')) {
            fileList.push(filePath);
        }
    }
    
    return fileList;
}

/**
 * Update CSS version in a link tag
 */
function updateCssVersion(linkTag) {
    // Match CSS files with or without version parameter
    const versionRegex = /(<link[^>]*href=["']([^"']*\.css))(\?v=(\d+))?(["'][^>]*>)/i;
    const match = linkTag.match(versionRegex);
    
    if (match) {
        const [, prefix, cssPath, versionParam, currentVersion, suffix] = match;
        const newVersion = currentVersion ? parseInt(currentVersion) + 1 : 1;
        return `${prefix}?v=${newVersion}${suffix}`;
    }
    
    return linkTag;
}

/**
 * Process an HTML file and update CSS versions
 */
function processHtmlFile(filePath) {
    console.log(`Processing: ${filePath}`);
    
    let content = fs.readFileSync(filePath, 'utf8');
    let updated = false;
    
    // Find all link tags for stylesheets
    const linkRegex = /<link[^>]*rel=["']stylesheet["'][^>]*>/gi;
    
    content = content.replace(linkRegex, (match) => {
        const newLink = updateCssVersion(match);
        if (newLink !== match) {
            updated = true;
            console.log(`  Updated: ${match.substring(0, 50)}...`);
        }
        return newLink;
    });
    
    if (updated) {
        fs.writeFileSync(filePath, content, 'utf8');
        console.log(`  ✓ File updated\n`);
    } else {
        console.log(`  - No CSS links found\n`);
    }
    
    return updated;
}

/**
 * Main function
 */
function main() {
    const rootDir = path.join(__dirname, '..');
    
    console.log('🔍 Finding HTML files...\n');
    const htmlFiles = findHtmlFiles(rootDir);
    
    console.log(`Found ${htmlFiles.length} HTML file(s)\n`);
    console.log('📝 Updating CSS versions...\n');
    
    let totalUpdated = 0;
    
    for (const file of htmlFiles) {
        if (processHtmlFile(file)) {
            totalUpdated++;
        }
    }
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log(`✅ Done! Updated ${totalUpdated} file(s)`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
}

// Run the script
main();
