import { defineConfig, defineDocs } from 'fumadocs-mdx/config';
import { metaSchema, pageSchema } from 'fumadocs-core/source/schema';

// 把 ```mermaid 代码块转成 <Mermaid chart=.../>(运行在 remark 阶段,早于 shiki 高亮,
// 故 mermaid 源不会被当普通代码高亮)。依赖无关:手写遍历 mdast,不引 unist-util-visit。
function remarkMermaid() {
  return (tree: { children?: unknown[] }) => {
    const walk = (node: { children?: unknown[] }) => {
      if (!Array.isArray(node.children)) return;
      node.children = node.children.map((child) => {
        const c = child as { type?: string; lang?: string; value?: string };
        if (c.type === 'code' && c.lang === 'mermaid') {
          return {
            type: 'mdxJsxFlowElement',
            name: 'Mermaid',
            attributes: [{ type: 'mdxJsxAttribute', name: 'chart', value: c.value ?? '' }],
            children: [],
          };
        }
        walk(c as { children?: unknown[] });
        return child;
      });
    };
    walk(tree);
  };
}

// You can customize Zod schemas for frontmatter and `meta.json` here
// see https://fumadocs.dev/docs/mdx/collections
export const docs = defineDocs({
  dir: 'content/docs',
  docs: {
    schema: pageSchema,
    postprocess: {
      includeProcessedMarkdown: true,
    },
  },
  meta: {
    schema: metaSchema,
  },
});

export default defineConfig({
  mdxOptions: {
    // 函数形式:在 fumadocs 内置 remark 插件(gfm/structure 等)之后追加 mermaid 转换,不覆盖内置。
    remarkPlugins: (v) => [...v, remarkMermaid],
  },
});
