import { CNB } from "@kevisual/cnb";
import fs from 'node:fs';
import path from 'node:path';

const _posts = path.join(process.cwd(), 'blog', 'source', '_posts')

export const cnb = new CNB({
    token: process.env.CNB_TOKEN!,
    cookie: process.env.CNB_COOKIE!
});

const issuesList = await cnb.issue.getList('abearxiong/blog', {
    page: 1,
    page_size: 1000
})

for (const issue of issuesList.data) {
    const res = await cnb.issue.getItem('abearxiong/blog', issue.number)
    console.log(res)
    if (res.code === 200) {
        const data = res.data
        const title = data.title;
        // @ts-ignore
        const content = data.body;
        // @ts-ignore
        const created_at = data.created_at;
        const updated_at = data.updated_at
        const labels = data.labels || [];
        
        const filename = `${issue.number}.md`
        const filepath = path.join(_posts, filename)

        const article = `---
title: ${title}
date: ${new Date(created_at)}
updated: ${new Date(updated_at)}
tags: ${labels.map((l: any) => l.name).join(', ')}
---

${content}
`

        fs.writeFileSync(filepath, article, 'utf-8')
        console.log(`已写入: ${issue.number}`)
    }
}
