import { defineUserConfig } from 'vitepress-export-pdf'
import userConfig from './config.mjs'

function extractLinksFromConfig(config: DefaultTheme.Config) {
  const links: string[] = []

  function extractLinks(sidebar: DefaultTheme.SidebarItem[]) {
    for (const item of sidebar) {
      if (item.items)
        extractLinks(item.items)

      else if (item.link)
        links.push(`${item.link}.html`)
    }
  }

  for (const key in config.sidebar)
    extractLinks(config.sidebar[key])

  return links
}

const links = extractLinksFromConfig(userConfig.themeConfig!)


export default defineUserConfig({
  sorter: (pageA, pageB) => {
  const routeOrder = [
    '/index.html',
    ...links,
  ]

    const aIndex = routeOrder.findIndex(route => route === pageA.path)
    const bIndex = routeOrder.findIndex(route => route === pageB.path)

    if (aIndex === -1 && bIndex === -1) {
      return pageA.path.localeCompare(pageB.path)
    }
    if (aIndex === -1) return 1
    if (bIndex === -1) return -1

    return aIndex - bIndex
  },
  outFile: 'HF-MES-v5.0-使用手册.pdf',
  outDir: 'docs',
  routePatterns: ['/**'],
  pdfOptions: {
    format: 'A4',
    margin: {
      top: '20mm',
      right: '15mm',
      bottom: '20mm',
      left: '15mm'
    },
    printBackground: true,
    preferCSSPageSize: true,
    displayHeaderFooter: true,
    headerTemplate: `
      <div style="font-size: 10px; width: 100%; text-align: center; color: #666; font-family: 'Microsoft YaHei', '微软雅黑', 'Microsoft YaHei UI', 'PingFang SC', sans-serif;">
        <span class="title"></span>
      </div>
    `,
    footerTemplate: `
      <div style="font-size: 10px; width: 100%; display: flex; justify-content: space-between; padding: 0 15mm; font-family: 'Microsoft YaHei', '微软雅黑', 'Microsoft YaHei UI', 'PingFang SC', sans-serif;">
        <span>HF-MES v5.0 使用手册</span>
        <span><span class="pageNumber"></span> / <span class="totalPages"></span></span>
      </div>
    `
  },
  pdfOutlines: true,
  puppeteerLaunchOptions: {
    headless: true,
    timeout: 60000,
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
      '--disable-gpu',
      '--disable-software-rasterizer',
      '--no-first-run',
      '--no-zygote',
      '--single-process',
      '--font-render-hinting=none',
      '--disable-font-subpixel-positioning',
      '--force-color-profile=srgb',
    ],
    env: {
      FC_LANG: 'zh-CN',
      LANG: 'zh_CN.UTF-8',
      LC_ALL: 'zh_CN.UTF-8',
    },
    dumpio: false,
  }
})
