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

const assetsDir = path.join(__dirname, '..', 'assets');
const optimizedDir = path.join(__dirname, '..', 'optimized', 'webp');

function ensureDir(dir) {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
}

async function convertToWebP(filePath) {
    const ext = path.extname(filePath).toLowerCase();
    if (!['.jpg', '.jpeg', '.png'].includes(ext)) return;

    const relativePath = path.relative(assetsDir, filePath);
    const webpPath = path.join(optimizedDir, relativePath.replace(/\.(jpg|jpeg|png)$/i, '.webp'));

    ensureDir(path.dirname(webpPath));

    try {
        await sharp(filePath)
            .webp({ quality: 80 })
            .toFile(webpPath);
        console.log(`Converted: ${filePath} -> ${webpPath}`);
    } catch (err) {
        console.error(`Failed to convert ${filePath}:`, err);
    }
}

function walkDir(dir) {
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            walkDir(fullPath);
        } else {
            convertToWebP(fullPath);
        }
    }
}

walkDir(assetsDir);