import { docs } from 'collections/server';
import { loader } from 'fumadocs-core/source';
import { lucideIconsPlugin } from 'fumadocs-core/source/lucide-icons';
import { openapi } from './openapi';
import { docsContentRoute, docsImageRoute, docsRoute } from './shared';

// 多源 loader:手写 MDX(docs)+ 由 OpenAPI spec 派生的虚拟 API 参考页(openapi)。
// openapi 页挂在 /docs/api 下,按 tag(≈ controller)分组。loaderPlugin 给侧栏加
// GET/POST 方法标记。See https://fumadocs.dev/docs/headless/source-api
export const source = loader(
  {
    docs: docs.toFumadocsSource(),
    openapi: await openapi.staticSource({ groupBy: 'tag', baseDir: 'api' }),
  },
  {
    baseUrl: docsRoute,
    plugins: [openapi.loaderPlugin(), lucideIconsPlugin()],
  },
);

export function getPageImage(page: (typeof source)['$inferPage']) {
  const segments = [...page.slugs, 'image.png'];

  return {
    segments,
    url: `${docsImageRoute}/${segments.join('/')}`,
  };
}

export function getPageMarkdownUrl(page: (typeof source)['$inferPage']) {
  const segments = [...page.slugs, 'content.md'];

  return {
    segments,
    url: `${docsContentRoute}/${segments.join('/')}`,
  };
}

export async function getLLMText(page: (typeof source)['$inferPage']) {
  // openapi 虚拟页没有 processed markdown,跳过正文。
  const processed = 'getText' in page.data ? await page.data.getText('processed') : '';

  return `# ${page.data.title} (${page.url})

${processed}`;
}
