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

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

let css = fs.readFileSync(cssPath, 'utf8');

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

const keptBlocks = [];
const usedFiles = new Set();
const allFoundFiles = new Set();
const fileRenames = new Map();

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

    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\(([^)]+\.woff2)\)/);

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

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

    allFoundFiles.add(filename);

    let keep = false;
    if (subset === 'latin' || subset === 'latin-ext') {
        if (family === 'Lato' && (weight === '400' || weight === '700')) {
            keep = true;
        } else if (family === 'Libre Franklin' && (weight === '400' || weight === '600' || weight === '700')) {
            keep = true;
        }
    }

    if (keep) {
        // e.g. lato-normal-400-latin.woff2
        const semanticName = `${family.toLowerCase().replace(/ /g, '-')}-${style}-${weight}-${subset}.woff2`;
        
        let newContent = content.replace(filename, semanticName);
        keptBlocks.push(`${subsetComment}\n@font-face {${newContent}}`);
        
        fileRenames.set(filename, semanticName);
        usedFiles.add(semanticName);
    }
}

// Perform file operations
const filesInDir = fs.readdirSync(fontsDir).filter(f => f.endsWith('.woff2'));

// Delete files not in fileRenames
let deletedCount = 0;
for (const file of filesInDir) {
    if (!fileRenames.has(file)) {
        try {
            fs.unlinkSync(path.join(fontsDir, file));
            deletedCount++;
        } catch (e) {
            console.error(`Failed to delete ${file}`, e);
        }
    }
}

// Rename files
let renamedCount = 0;
for (const [oldName, newName] of fileRenames.entries()) {
    const oldPath = path.join(fontsDir, oldName);
    const newPath = path.join(fontsDir, newName);
    if (fs.existsSync(oldPath)) {
        fs.renameSync(oldPath, newPath);
        renamedCount++;
    } else if (fs.existsSync(newPath)) {
        // already renamed
    }
}

// Write updated CSS
fs.writeFileSync(cssPath, keptBlocks.join('\n\n'));

console.log(`Kept ${keptBlocks.length} @font-face blocks.`);
console.log(`Renamed ${renamedCount} files.`);
console.log(`Deleted ${deletedCount} unused files.`);
