name: ffctk-release

# 触发：
#   - tag 推送 `ffctk-v*`（如 `ffctk-v0.1.0`）→ 三平台 cross-compile + 上传 Release
#   - workflow_dispatch：手动触发（debug）
#
# 输出：
#   - 4 个 binary：ffctk-linux-x64 / ffctk-macos-x64 / ffctk-macos-arm64 / ffctk-win-x64.exe
#   - SHA256SUMS 校验文件
#   - install.sh / install.ps1（替换 ${FFCTK_INSTALL_BASE} 占位为本次 Release URL）
#
# 安全：未签名 binary（内部工具，节省 Apple Dev / EV 证书成本）
#   - macOS 走 `xattr -d com.apple.quarantine` 绕 Gatekeeper（install.sh 自动处理）
#   - Windows 走 `Unblock-File`（install.ps1 自动处理）
#
# 闭环载体：Gitea Release artifact

on:
  push:
    tags:
      - 'ffctk-v*'
  workflow_dispatch:
    inputs:
      tag:
        description: '手动指定 tag（必须以 ffctk-v 开头）'
        required: true
        default: 'ffctk-v0.1.0'

permissions:
  contents: write  # 创建 Release + 上传 artifact

jobs:
  build:
    name: Cross-compile ffctk
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: tools/ffctk
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install deps
        run: npm ci --no-audit --no-fund

      - name: Build TS
        run: npm run build

      - name: Cross-compile via @yao-pkg/pkg (one target per binary，保证 arch 后缀)
        # pkg 多 target 会把同 platform 不同 arch 的产物互相覆盖（macos-x64 + macos-arm64
        # 都叫 ffctk-macos），所以每个 target 单独跑一次 + 显式 --output 路径。
        run: |
          mkdir -p dist-bin
          npx --yes @yao-pkg/pkg . --targets node20-linux-x64    --output dist-bin/ffctk-linux-x64
          npx --yes @yao-pkg/pkg . --targets node20-linux-arm64  --output dist-bin/ffctk-linux-arm64
          npx --yes @yao-pkg/pkg . --targets node20-macos-x64    --output dist-bin/ffctk-macos-x64
          npx --yes @yao-pkg/pkg . --targets node20-macos-arm64  --output dist-bin/ffctk-macos-arm64
          npx --yes @yao-pkg/pkg . --targets node20-win-x64      --output dist-bin/ffctk-win-x64.exe
          ls -la dist-bin/

      - name: Generate SHA256SUMS
        run: |
          cd dist-bin
          sha256sum * > SHA256SUMS
          cat SHA256SUMS

      - name: Substitute FFCTK_INSTALL_BASE in install scripts
        env:
          RELEASE_BASE: ${{ github.server_url }}/${{ github.repository }}/releases/download/${{ github.ref_name }}
        run: |
          sed "s#\${FFCTK_INSTALL_BASE:-https://ffai.faradayfuture.com}#${RELEASE_BASE}#g" install/install.sh > dist-bin/install.sh
          sed "s#https://ffai.faradayfuture.com#${RELEASE_BASE}#g" install/install.ps1 > dist-bin/install.ps1
          chmod +x dist-bin/install.sh

      - name: Upload to Gitea Release
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
          TAG: ${{ github.ref_name }}
        run: |
          set -e
          # 显式 token 非空 guard：未配 secret 时 curl 走空鉴权 401 静默失败，workflow 仍绿
          # 易让作者误以为 release artifact 已上传；改成入口处硬阻断
          if [ -z "${GITEA_TOKEN}" ]; then
            echo "::error::GITEA_TOKEN secret is missing. Configure it in repo settings → Actions → Secrets." >&2
            exit 1
          fi
          # 假设 Gitea action runner 已通过 token 鉴权；用 curl 上传 artifact
          # Release 由 push tag 自动创建（Gitea 行为）；这里仅上传 artifact
          API="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/tags/${TAG}"
          REL_ID=$(curl -s -H "Authorization: token ${GITEA_TOKEN}" "${API}" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id',''))")
          if [ -z "${REL_ID}" ]; then
            echo "Release not found, creating…"
            REL_ID=$(curl -s -X POST -H "Authorization: token ${GITEA_TOKEN}" -H "Content-Type: application/json" \
              -d "{\"tag_name\":\"${TAG}\",\"name\":\"ffctk ${TAG}\",\"body\":\"FF AI Coding Tools Tracker binary release\"}" \
              "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases" \
              | python3 -c "import json,sys; print(json.load(sys.stdin).get('id',''))")
          fi
          cd dist-bin
          for f in * ; do
            echo "Uploading $f"
            curl -s -X POST \
              -H "Authorization: token ${GITEA_TOKEN}" \
              -F "attachment=@${f}" \
              "${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${REL_ID}/assets?name=${f}"
          done
