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,400;0,600;0,700;1,400;1,600;1,700&family=Lato:ital,wght@0,400;0,700;1,400;1,700&display=swap';

const fontsDir = path.join(__dirname, '..', 'assets', 'fonts');

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() {
    // 1. Delete all existing fonts
    const files = fs.readdirSync(fontsDir);
    for (const f of files) {
        if (f.endsWith('.woff2') || f === 'fonts.css') {
            fs.unlinkSync(path.join(fontsDir, f));
        }
    }

    console.log("Fetching Google Fonts CSS...");
    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' }
    });

    const blocks = [];
    const blockRegex = /(\/\*\s*([a-zA-Z0-9-]+)\s*\*\/)\s*@font-face\s*\{([^}]+)\}/g;
    let match;

    while ((match = blockRegex.exec(css)) !== null) {
        const subsetComment = match[1];
        const subset = match[2];
        let content = match[3];

        if (subset !== 'latin' && subset !== 'latin-ext') continue;

        const familyMatch = content.match(/font-family:\s*'([^']+)'/);
        const weightMatch = content.match(/font-weight:\s*(\d+)/);
        const styleMatch = content.match(/font-style:\s*([a-zA-Z]+)/);
        const urlMatch = content.match(/url\((https:\/\/[^)]+\.woff2)\)/);

        if (!familyMatch || !weightMatch || !styleMatch || !urlMatch) continue;

        const family = familyMatch[1];
        const weight = weightMatch[1];
        const style = styleMatch[1];
        const fontUrl = urlMatch[1];

        // Ensure we only process specified weights (should be true based on the requested URL)
        if (family === 'Lato' && !['400', '700'].includes(weight)) continue;
        if (family === 'Libre Franklin' && !['400', '600', '700'].includes(weight)) continue;

        const weightName = weight === '400' ? 'regular' : weight === '600' ? 'semibold' : 'bold';
        const semanticName = `${family.toLowerCase().replace(/ /g, '-')}-${style === 'normal' ? weightName : style + '-' + weightName}-${weight}-${subset}.woff2`;

        const dest = path.join(fontsDir, semanticName);
        console.log(`Downloading ${semanticName}...`);
        await downloadFile(fontUrl, dest);

        content = content.replace(fontUrl, semanticName);
        blocks.push(`${subsetComment}\n@font-face {${content}}`);
    }

    fs.writeFileSync(path.join(fontsDir, 'fonts.css'), blocks.join('\n\n'));
    console.log(`Saved ${blocks.length} fonts and updated fonts.css`);
}

main().catch(console.error);
