const { glob, mkdir, readFile, writeFile } = require('node:fs/promises');
const readline = require('node:readline/promises');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

async function main() {
    await mkdir('blog-migrated', { recursive: true });
    if (glob('blog-migrated/*').length) {
        const answer = await rl.question(
            'blog-migrated destination folder must be empty before starting, delete contents now?',
        );
        if (!/^[yY]([eE][sS])?$/.exec(answer)) {
            process.exit(0);
        }
    }

    const files = glob('./blog/*.md');
    const writeOps = [];
    for await (const file of files) {
        const fileContent = (await readFile(file)).toString();

        const [firstDelimiterMatch, secondDelimiterMatch] = [...fileContent.matchAll(/^---$/gm)];
        const frontMatter = fileContent.slice(
            firstDelimiterMatch.index + 4, secondDelimiterMatch.index
        );
        const content = fileContent.slice(0, firstDelimiterMatch.index).concat(
            fileContent.slice(secondDelimiterMatch.index + 4),
        );

        const indentedContent = content.trim().replaceAll(/^/gm, '  ');
        const yamlContent = `${frontMatter}\ncontent: |\n${indentedContent}\n`;
        const filename = file.replaceAll(/^.*blog\//g, 'blog-migrated/').replaceAll(/.md$/g, '.yaml')
        writeOps.push(writeFile(filename, yamlContent));
    }

    await Promise.all(writeOps);
}

main().then(() => {
    console.log('Done!')
    process.exit(0);
}).catch((err) => {
    throw err;
});
