name: 构建发布

permissions:
  contents: read

on:
  push:
    tags:
      - 'v*'               # 推送 tag 时触发发布
  workflow_dispatch:        # 支持手动触发
    inputs:
      publish-to-pypi:
        description: '发布至 PyPI (true/false)'
        required: false
        default: 'false'

env:
  CARGO_TERM_COLOR: always
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  # ============================================================
  # 1. 校验 & 发布
  #    解析 chanlun-py 依赖的版本号 → 检查 crates.io 是否可用 →
  #    不可用时检查本地 chanlun 版本是否匹配 → 匹配则自动发布 →
  #    等待索引同步
  # ============================================================
  check-version:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.parse.outputs.version }}
    steps:
      - uses: actions/checkout@v4

      - name: 安装 Rust 工具链
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - name: 解析 chanlun-py 依赖的 chanlun 版本
        id: parse
        working-directory: chanlun-py
        run: |
          VER=$(grep -oP 'chanlun\s*=\s*"=?\s*\K[0-9]+\.[0-9]+\.[0-9]+(?=")' Cargo.toml | head -1)
          if [ -z "$VER" ]; then
            echo "::error::无法从 chanlun-py/Cargo.toml 解析 chanlun 版本号"
            echo "请确保 Cargo.toml 中包含: chanlun = \"=X.Y.Z\""
            exit 1
          fi
          echo "version=$VER" >> $GITHUB_OUTPUT
          echo "依赖的 chanlun 版本: $VER"

      - name: 解析本地 chanlun 核心库版本
        id: local-ver
        working-directory: chanlun
        run: |
          VER=$(grep -oP '^version\s*=\s*"\K[0-9]+\.[0-9]+\.[0-9]+(?=")' Cargo.toml | head -1)
          echo "version=$VER" >> $GITHUB_OUTPUT
          echo "本地 chanlun 版本: $VER"

      - name: 检查 crates.io 并决定是否发布
        id: check
        run: |
          DEP_VER="${{ steps.parse.outputs.version }}"
          LOCAL_VER="${{ steps.local-ver.outputs.version }}"

          HTTP_CODE=$(curl -sS -o /dev/null -w "%{http_code}" \
            -H "User-Agent: chanlun-rs/ci" \
            "https://crates.io/api/v1/crates/chanlun/$DEP_VER")

          if [ "$HTTP_CODE" = "200" ]; then
            echo "chanlun $DEP_VER 在 crates.io 已可用，无需发布"
            echo "need-publish=false" >> $GITHUB_OUTPUT
            exit 0
          fi

          echo "chanlun $DEP_VER 在 crates.io 不存在 (HTTP $HTTP_CODE)"

          if [ "$DEP_VER" != "$LOCAL_VER" ]; then
            echo "::error::本地 chanlun 版本 ($LOCAL_VER) 与依赖版本 ($DEP_VER) 不匹配"
            echo ""
            echo "请先发布 chanlun 核心库至 crates.io:"
            echo "  cd chanlun && cargo publish"
            echo ""
            echo "或修改 chanlun-py/Cargo.toml 中的版本号为已发布版本"
            exit 1
          fi

          echo "本地版本 $LOCAL_VER 与依赖一致，将自动发布 chanlun 至 crates.io"
          echo "need-publish=true" >> $GITHUB_OUTPUT

      - name: 格式检查
        if: steps.check.outputs.need-publish == 'true'
        working-directory: chanlun
        run: cargo fmt --check

      - name: Lint 检查
        if: steps.check.outputs.need-publish == 'true'
        working-directory: chanlun
        run: cargo clippy

      - name: 运行测试
        if: steps.check.outputs.need-publish == 'true'
        working-directory: chanlun
        run: cargo test

      - name: 验证打包
        if: steps.check.outputs.need-publish == 'true'
        working-directory: chanlun
        run: cargo publish --dry-run --allow-dirty

      - name: 登录 crates.io 并发布
        if: steps.check.outputs.need-publish == 'true'
        run: |
          cargo login ${{ secrets.CARGO_TOKEN }}
          cd chanlun && cargo publish --allow-dirty

      - name: 等待 crates.io 索引同步
        if: steps.check.outputs.need-publish == 'true'
        run: |
          DEP_VER="${{ steps.parse.outputs.version }}"
          echo "等待 crates.io 索引同步 (最多 2 分钟)..."
          for i in $(seq 1 12); do
            HTTP_CODE=$(curl -sS -o /dev/null -w "%{http_code}" \
              -H "User-Agent: chanlun-rs/ci" \
              "https://crates.io/api/v1/crates/chanlun/$DEP_VER")
            if [ "$HTTP_CODE" = "200" ]; then
              echo "chanlun $DEP_VER 已在 crates.io 可用 (尝试 $i/12)"
              exit 0
            fi
            echo "  等待中... ($i/12)"
            sleep 10
          done
          echo "::error::等待超时：chanlun $DEP_VER 在 crates.io 仍不可用"
          exit 1

  # ============================================================
  # 2. 构建 wheel — Linux x86_64 (manylinux)
  # ============================================================
  linux-x86_64:
    needs: [check-version]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: 安装 Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: 安装 Rust 工具链
        uses: dtolnay/rust-toolchain@stable

      - name: 更新 cargo 索引（含重试）
        working-directory: chanlun-py
        run: |
          for i in $(seq 1 6); do
            if cargo update 2>&1; then
              echo "cargo update 成功"
              exit 0
            fi
            echo "cargo update 失败，重试... ($i/6)"
            sleep 10
          done
          echo "::error::cargo update 失败"
          exit 1

      - name: 构建 wheel (manylinux)
        uses: PyO3/maturin-action@v1
        with:
          target: x86_64
          working-directory: chanlun-py
          args: --release --out dist
          manylinux: auto

      - name: 上传 wheel 产物
        uses: actions/upload-artifact@v4
        with:
          name: wheels-linux-x86_64
          path: chanlun-py/dist/

  # ============================================================
  # 3. 构建 wheel — macOS (x86_64 + arm64)
  # ============================================================
  macos:
    needs: [check-version]
    runs-on: macos-latest
    strategy:
      matrix:
        target: [x86_64, aarch64]
    steps:
      - uses: actions/checkout@v4

      - name: 安装 Rust 工具链
        uses: dtolnay/rust-toolchain@stable

      - name: 安装 Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: 更新 cargo 索引（含重试）
        working-directory: chanlun-py
        run: |
          for i in $(seq 1 6); do
            if cargo update 2>&1; then
              echo "cargo update 成功"
              exit 0
            fi
            echo "cargo update 失败，重试... ($i/6)"
            sleep 10
          done
          echo "::error::cargo update 失败"
          exit 1

      - name: 构建 wheel
        uses: PyO3/maturin-action@v1
        with:
          target: ${{ matrix.target }}
          working-directory: chanlun-py
          args: --release --out dist

      - name: 上传 wheel 产物
        uses: actions/upload-artifact@v4
        with:
          name: wheels-macos-${{ matrix.target }}
          path: chanlun-py/dist/

  # ============================================================
  # 4. 构建 wheel — Windows x86_64
  # ============================================================
  windows:
    needs: [check-version]
    runs-on: windows-latest
    strategy:
      matrix:
        target: [x64]
    steps:
      - uses: actions/checkout@v4

      - name: 安装 Rust 工具链
        uses: dtolnay/rust-toolchain@stable

      - name: 安装 Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: 更新 cargo 索引（含重试）
        working-directory: chanlun-py
        shell: pwsh
        run: |
          for ($i = 1; $i -le 6; $i++) {
            cargo update
            if ($LASTEXITCODE -eq 0) {
              Write-Host "cargo update 成功"
              exit 0
            }
            Write-Host "cargo update 失败，重试... ($i/6)"
            Start-Sleep -Seconds 10
          }
          Write-Host "::error::cargo update 失败"
          exit 1

      - name: 构建 wheel
        uses: PyO3/maturin-action@v1
        with:
          target: ${{ matrix.target }}
          working-directory: chanlun-py
          args: --release --out dist

      - name: 上传 wheel 产物
        uses: actions/upload-artifact@v4
        with:
          name: wheels-windows-${{ matrix.target }}
          path: chanlun-py/dist/

  # ============================================================
  # 5. 源码分发包 (sdist)
  # ============================================================
  sdist:
    needs: [check-version]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: 安装 Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: 安装 Rust 工具链
        uses: dtolnay/rust-toolchain@stable

      - name: 构建 sdist
        uses: PyO3/maturin-action@v1
        with:
          command: sdist
          working-directory: chanlun-py
          args: --out dist

      - name: 上传 sdist 产物
        uses: actions/upload-artifact@v4
        with:
          name: wheels-sdist
          path: chanlun-py/dist/

  # ============================================================
  # 6. 发布至 PyPI
  # ============================================================
  publish:
    needs: [linux-x86_64, macos, windows, sdist]
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v') || github.event.inputs.publish-to-pypi == 'true'
    permissions:
      id-token: write

    steps:
      - name: 下载所有产物
        uses: actions/download-artifact@v4
        with:
          path: dist/
          pattern: wheels-*
          merge-multiple: true

      - name: 列出产物
        run: ls -la dist/

      - name: 发布至 PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          packages-dir: dist/
