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

const cssDir = 'c:/xampp/htdocs/doormileweb/assets/css';
const files = fs.readdirSync(cssDir).filter(f => f.endsWith('.css'));

files.forEach(file => {
    const filePath = path.join(cssDir, file);
    let content = fs.readFileSync(filePath, 'utf8');
    let changed = false;

    // 1. Replace external domains and /wp-content/ in URLs
    // Pattern: url("https://.../wp-content/.../file.ext") -> url("/doormileweb/assets/.../file.ext")
    // This is tricky because we don't know the exact mapping. 
    // But most fonts/images should be in assets/fonts/ or assets/images/.
    
    // Specifically for fonts
    content = content.replace(/url\(['"]?(?:https?:\/\/[^/]+)?(?:\/themes\/[^/]+)?\/wp-content\/[^'"]+\/([^'"]+\.(?:woff2?|ttf|eot|svg))['"]?\)/gi, (match, filename) => {
        changed = true;
        return `url(/doormileweb/assets/fonts/${filename})`;
    });

    // Specifically for images
    content = content.replace(/url\(['"]?(?:https?:\/\/[^/]+)?(?:\/themes\/[^/]+)?\/wp-content\/[^'"]+\/([^'"]+\.(?:jpg|png|gif|svg|webp))['"]?\)/gi, (match, filename) => {
        changed = true;
        return `url(/doormileweb/assets/images/${filename})`;
    });

    // 2. Replace relative paths to fonts
    // Pattern: url(../../fonts/file.ext) -> url(/doormileweb/assets/fonts/file.ext)
    content = content.replace(/url\(['"]?(?:\.\.\/)+fonts\/([^'"]+)['"]?\)/gi, (match, filename) => {
        changed = true;
        return `url(/doormileweb/assets/fonts/${filename})`;
    });

    // Patterns with /plugins/ elementor ...
    content = content.replace(/url\(['"]?(?:\.\.\/)+plugins\/elementor\/assets\/lib\/font-awesome\/webfonts\/([^'"]+)['"]?\)/gi, (match, filename) => {
        changed = true;
        return `url(/doormileweb/assets/fonts/${filename})`;
    });
    content = content.replace(/url\(['"]?(?:\.\.\/)+plugins\/elementor\/assets\/lib\/eicons\/fonts\/([^'"]+)['"]?\)/gi, (match, filename) => {
        changed = true;
        return `url(/doormileweb/assets/fonts/${filename})`;
    });

    // 3. Fix /assets/fonts/ -> /doormileweb/assets/fonts/
    content = content.replace(/url\(?['"]?\/assets\/fonts\/([^'"]+)['"]?\)?/gi, (match, pathPart) => {
        // match might include url( or just the path if I'm not careful.
        // Let's refine the regex.
        if (match.startsWith('url(')) {
            changed = true;
            return `url(/doormileweb/assets/fonts/${pathPart})`;
        }
        return match;
    });
    
    // General /assets/ fix
    content = content.replace(/url\(['"]?\/assets\/([^'"]+)['"]?\)/gi, (match, pathPart) => {
        changed = true;
        return `url(/doormileweb/assets/${pathPart})`;
    });

    if (changed) {
        console.log(`Updated paths in ${file}`);
        fs.writeFileSync(filePath, content);
    }
});
