const { glob } = require('glob');
const fs = require('fs');
const path = require('path');

(async () => {
    const imagesDirectory = path.join(__dirname, 'src', 'images');

    if (!fs.existsSync(imagesDirectory)) {
        fs.mkdirSync(imagesDirectory, { recursive: true });
    }

    const markdownFiles = await glob('src/blog/posts/**/*.md');
    const imageRegex = /!\[(.*?)\]\((.*?)\)/g;
    const imageRegex2 = /<img.*?src="(.*?)".*?>/g;

    for (const markdownFile of markdownFiles) {
        const markdown = fs.readFileSync(markdownFile, 'utf-8');
        const images = [...markdown.matchAll(imageRegex), ...markdown.matchAll(imageRegex2)];
        for (const image of images) {
            const imageUrl = image[2] || image[1];
            const imageFile = imageUrl.split('/').pop();
            const imagePath = path.join(imagesDirectory, imageFile);
            if (!fs.existsSync(imagePath)) {
                console.log(`Downloading ${imageUrl} to ${imagePath}`);
                const imageResponse = await fetch(imageUrl);
                const imageBuffer = Buffer.from(await imageResponse.arrayBuffer());
                fs.writeFileSync(imagePath, imageBuffer);
            }

            const newMarkdown = markdown.replace(imageUrl, `./src/images/${imageFile}`);
            fs.writeFileSync(markdownFile, newMarkdown);
        }
    }
})();