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

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

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

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

    const relativePath = path.relative(assetsDir, filePath);
    const resizedPath = path.join(optimizedDir, relativePath);

    ensureDir(path.dirname(resizedPath));

    try {
        await sharp(filePath)
            .resize({ width: 800, withoutEnlargement: true })
            .toFile(resizedPath);
        console.log(`Resized: ${filePath} -> ${resizedPath}`);
    } catch (err) {
        console.error(`Failed to resize ${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 {
            resizeImage(fullPath);
        }
    }
}

walkDir(assetsDir);