name: Go Build & Release

on:
  workflow_dispatch:  # 仅支持手动触发
    inputs:
      releaseVersion:  # 手动输入版本号（可选，默认自动生成）
        description: '自定义Release版本号（如 v1.0.2）'
        required: false
        type: string

jobs:
  # 准备版本号（优先使用手动输入，否则自动生成）
  prepare-version:
    runs-on: ubuntu-latest
    outputs:
      build_version: ${{ steps.set-version.outputs.version }}
    
    steps:
      - name: Set build version
        id: set-version
        run: |
          # 如果手动输入了版本号，则使用输入值；否则自动生成
          if [ -n "${{ github.event.inputs.releaseVersion }}" ]; then
            echo "version=${{ github.event.inputs.releaseVersion }}" >> $GITHUB_OUTPUT
          else
            # 自动生成格式：vYYYYMMDD-HHMMSS（带v前缀符合Release规范）
            echo "version=v$(date +'%Y%m%d-%H%M%S')" >> $GITHUB_OUTPUT
          fi

  build:
    needs: prepare-version
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4

    - name: 缓存Go依赖
      id: go-cache
      uses: actions/cache@v3
      with:
          path: ~/go/pkg/mod
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.mod') }}
          restore-keys: |
            ${{ runner.os }}-go-

    - name: Set up Go
      uses: actions/setup-go@v4
      with:
        go-version: '1.20'

    - name: 编译logic服务
      run: go build -o ./public/logic_${{ needs.prepare-version.outputs.build_version }} -v ./logic

    - name: Upload Build Artifact
      uses: actions/upload-artifact@v4
      with:
          name: logic_${{ needs.prepare-version.outputs.build_version }}
          path: ./public/logic_${{ needs.prepare-version.outputs.build_version }}

    - name: 推送到服务器
      uses: easingthemes/ssh-deploy@main
      env:
          SSH_PRIVATE_KEY: ${{ secrets.BLAZING }}
          REMOTE_HOST: "82.23.177.97"
          REMOTE_USER: "root"
          SOURCE: "public/"
          TARGET: "/home/"
          ARGS: "-avz --chown=git:git"

  # 自动创建GitHub Release
  create-release:
    needs: [prepare-version, build]
    permissions:
      contents: write  # 必须的Release创建权限
    runs-on: ubuntu-latest
    
    steps:
      - name: Download build artifact
        uses: actions/download-artifact@v4
        with:
          name: logic_${{ needs.prepare-version.outputs.build_version }}
          path: ./public

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ needs.prepare-version.outputs.build_version }}  # 标签名=版本号
          name: Release ${{ needs.prepare-version.outputs.build_version }}  # Release标题
          body: |
            ## 自动构建发布
            - 版本号: ${{ needs.prepare-version.outputs.build_version }}
            - 触发方式: 手动触发
            - 构建时间: ${{ github.event.repository.updated_at }}
          files: ./public/logic_${{ needs.prepare-version.outputs.build_version }}  # 上传构建产物
          draft: false  # 直接发布，不存草稿
          prerelease: false  # 标记为正式版本
