const fs = require('fs');
const path = require('path');
const posts = require('./src/_data/old_posts');

const htmlDecode = (input) => {
    const doc = new DOMParser().parseFromString(input, "text/html");
    return doc.documentElement.textContent;
  }

  
(async () => {
    const postList = await posts();

    const postsDirectory = path.join(__dirname, 'src', 'blog', 'posts');
    if (!fs.existsSync(postsDirectory)) {
        fs.mkdirSync(postsDirectory, { recursive: true });
    }

    for (const post of postList) {
        const date = new Date(post.date);
        const dir = path.join(__dirname, 'src', 'blog', 'posts', date.getFullYear().toString(), (date.getMonth() + 1).toString());
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        const postPath = path.join(dir, `${post.slug}.md`);
        const postContent = `---
title: "${post.title.rendered}"
date: ${post.date}
slug: ${post.slug}
${post.tags.length ? `tags: [${post.tags.map(tag => tag.slug).join(', ')}]` : ''}
---
${post.markdown.replaceAll('\\\'','\'')}
`;
        fs.writeFileSync(postPath, postContent);
    }
})();