name: Build Linux Binaries (x86_64 & ARM)

on:
  workflow_dispatch:
  push:
    tags:
      - "build.*"

jobs:
  build_pyc:
    name: Build for pyc files only
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          repository: dataelement/bisheng-telemetry-search
          token: ${{ secrets.CROSS_REPO_TOKEN }}
          path: bisheng-telemetry-search

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'

      - name: Build and Clean Artifacts
        working-directory: ./bisheng-telemetry-search/telemetry_search
        run: |
          # 执行构建
          python -m compileall -b .
          
          # 在上传前彻底清理源代码和中间文件
          # 即使 build_all.py 做了清理，这里再次强制清理，防止 .c 文件泄露
          find . -name "*.py" -delete
          find . -name "__pycache__" -exec rm -rf {} +
          
          # 准备输出
          mkdir ../../build_output
          cp -r ./* ../../build_output/
          
          echo "Listing artifacts to be uploaded:"
          ls -R ../../build_output/

      - name: Upload PYC Artifacts
        uses: actions/upload-artifact@v4
        with:
          name: telemetry_search
          path: ./build_output/*

  deploy_to_sso_project:
    name: Deploy Artifacts to SSO Project
    needs: [ build_pyc ]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout SSO Project
        uses: actions/checkout@v4
        with:
          repository: dataelement/bisheng
          token: ${{ secrets.CROSS_REPO_TOKEN }}
          # 使用 ref 指定分支，而不是 base
          ref: feat/2.3.0
          path: bisheng
          # 确保拉取完整的历史以便正确提交
          fetch-depth: 0

      - name: Download PYC Artifacts
        uses: actions/download-artifact@v4
        with:
          name: telemetry_search
          path: ./telemetry_search

      - name: Merge and Place Files
        run: |
          
          find ./telemetry_search -name "*.py" -delete
          
          # 移动到目标仓库目录
          cp -r ./telemetry_search ./bisheng/src/backend/bisheng/
          
          echo "Final content of target directory:"
          ls -lh ./bisheng/src/backend/bisheng/telemetry_search

      - name: Commit and Push changes
        working-directory: ./bisheng
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          
          git add .
          
          # 检查是否有变更，有才提交
          if git diff --staged --quiet; then
            echo "No changes to commit"
          else
            git commit -m "chore: update telemetry_search build artifacts [skip ci]"
            git push origin feat/2.3.0
          fi