# 工作流名称：Publish Docs
# 该工作流用于在推送标签或手动触发时构建并部署文档到 GitHub Pages

name: Publish Docs

# 触发条件配置
# 当推送以 'v' 开头的标签时触发，或者通过 GitHub UI 手动触发
on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

# 权限配置
# 配置工作流所需的权限：
# - contents: read（读取仓库内容）
# - pages: write（写入 GitHub Pages）
# - id-token: write（写入身份令牌）
permissions:
  contents: read
  pages: write
  id-token: write

# 并发控制配置
# 设置并发组为 "pages"，并且不允许取消正在进行的任务
concurrency:
  group: pages
  cancel-in-progress: false

# 定义工作流中的任务
jobs:
  # 构建和部署任务
  build-and-deploy:
    # 条件判断：仅当推送的是正式版本标签（不包含预发布标识）或手动触发时执行
    if: |
      (startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, '-'))
      || github.event_name == 'workflow_dispatch'

    # 指定运行环境为最新版 Ubuntu
    runs-on: ubuntu-latest

    # 环境配置
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}

    # 步骤定义
    steps:
      # 检出代码
      - name: Checkout
        uses: actions/checkout@v6

      # 按 GitHub Pages 官方流程初始化部署元数据。
      - name: Configure GitHub Pages
        uses: actions/configure-pages@v5

      # 安装 Bun 运行时
      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      # 安装项目依赖
      - name: Install Dependencies
        working-directory: docs
        run: bun install

      # 构建 VitePress 文档
      - name: Build VitePress
        working-directory: docs
        run: bun run build
      
      # 生成 LLM 索引文件
      - name: Make docs LLM ready
        uses: demodrive-ai/llms-txt-action@v1
        with:
          docs_dir: docs/.vitepress/dist
          sitemap_path: sitemap.xml
          skip_llms_txt: 'false'
          skip_llms_full_txt: 'false'
          skip_md_files: 'false'

      # 在上传前校验 LLM 索引产物，避免部署出“步骤成功但文件缺失”的 Pages 站点。
      - name: Verify LLM artifacts
        run: |
          test -f docs/.vitepress/dist/sitemap.xml
          test -f docs/.vitepress/dist/llms.txt
          test -f docs/.vitepress/dist/llms-full.txt

          md_count="$(find docs/.vitepress/dist -type f -name '*.md' | wc -l)"
          if [ "$md_count" -eq 0 ]; then
            echo "Expected llms-txt-action to generate page-level markdown files, but none were found."
            exit 1
          fi

          echo "Generated $md_count markdown files for LLM ingestion."
      
      # 上传构建产物作为 Pages 部署工件
      - name: Upload Pages Artifact
        uses: actions/upload-pages-artifact@v4
        with:
          path: docs/.vitepress/dist

      # 将文档部署到 GitHub Pages
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v5
