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

const cssUrl = 'https://fonts.googleapis.com/css2?family=Libre+Franklin:ital,wght@0,100..900;1,100..900&family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swap';

const fontsDir = path.join(__dirname, '..', 'assets', 'fonts');
if (!fs.existsSync(fontsDir)) fs.mkdirSync(fontsDir, { recursive: true });

const fetchUrl = (url, options = {}) => {
    return new Promise((resolve, reject) => {
        https.get(url, options, (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 Google Fonts CSS...");
    // Must spoof modern browser to get woff2
    const css = await fetchUrl(cssUrl, {
        headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36' }
    });

    let localCss = css;
    const urlRegex = /url\((https:\/\/[^)]+\.woff2)\)/g;
    let match;
    let count = 0;

    while ((match = urlRegex.exec(css)) !== null) {
        const fontUrl = match[1];
        const filename = path.basename(new URL(fontUrl).pathname);
        const dest = path.join(fontsDir, filename);

        if (!fs.existsSync(dest)) {
            console.log(`Downloading ${filename}...`);
            await downloadFile(fontUrl, dest);
        }

        localCss = localCss.replace(fontUrl, `assets/fonts/${filename}`);
        count++;
    }

    fs.writeFileSync(path.join(__dirname, '..', 'assets', 'fonts', 'fonts.css'), localCss);
    console.log(`Downloaded ${count} font files and saved fonts.css`);
}

main().catch(console.error);
