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

const fetchUrl = (url) => {
    return new Promise((resolve, reject) => {
        https.get(url, (res) => {
            let data = '';
            res.on('data', chunk => data += chunk);
            res.on('end', () => resolve(data));
        }).on('error', reject);
    });
};

const downloadFile = (url, dest) => {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(dest);
        https.get(url, (response) => {
            response.pipe(file);
            file.on('finish', () => {
                file.close(resolve);
            });
        }).on('error', (err) => {
            fs.unlink(dest, () => reject(err));
        });
    });
};

async function main() {
    console.log("Fetching home-08...");
    const html = await fetchUrl('https://solvior.themejunction.net/home-08/');
    
    // Find CSS links
    const cssRegex = /<link[^>]+rel=['"]stylesheet['"][^>]+href=['"]([^'"]+)['"]/gi;
    let match;
    const cssUrls = [];
    while ((match = cssRegex.exec(html)) !== null) {
        let cssUrl = match[1];
        if (cssUrl.startsWith('/')) cssUrl = 'https://solvior.themejunction.net' + cssUrl;
        if (!cssUrl.includes('google') && !cssUrl.includes('elementor')) {
            cssUrls.push(cssUrl);
        }
    }
    
    console.log(`Found ${cssUrls.length} CSS files.`);
    
    // Create fonts dir
    const fontsDir = path.join(__dirname, '..', 'assets', 'fonts');
    if (!fs.existsSync(fontsDir)) fs.mkdirSync(fontsDir, { recursive: true });
    
    let allCss = '';
    for (const url of cssUrls) {
        console.log("Fetching CSS: " + url);
        try {
            const css = await fetchUrl(url);
            allCss += "\n" + css;
        } catch(e) {
            console.error("Failed to fetch " + url);
        }
    }
    
    fs.writeFileSync(path.join(__dirname, 'all.css'), allCss);
    console.log("Saved all.css. length: " + allCss.length);
}

main().catch(console.error);
