name: Build and Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

jobs:
  build:
    name: Build Go Binaries
    runs-on: ubuntu-latest
    strategy:
      matrix:
        goos: [linux, windows, darwin]
        goarch: [amd64, arm64]
        exclude:
          - goos: windows
            goarch: arm64
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
    
    - name: Set up Go
      uses: actions/setup-go@v4
      with:
        go-version: '1.21'
    
    - name: Install dependencies
      run: go mod download
    
    - name: Build binary
      env:
        GOOS: ${{ matrix.goos }}
        GOARCH: ${{ matrix.goarch }}
      run: |
        mkdir -p build
        BINARY_NAME=chuan
        if [ "$GOOS" = "windows" ]; then
          BINARY_NAME="${BINARY_NAME}.exe"
        fi
        
        VERSION=${GITHUB_REF_NAME:-dev}
        BUILD_TIME=$(date +'%Y-%m-%d %H:%M:%S')
        
        go build -ldflags "-X main.Version=${VERSION} -X main.BuildTime='${BUILD_TIME}'" \
          -o build/${BINARY_NAME} cmd/main.go
        
        # 创建发布包
        cd build
        if [ "$GOOS" = "windows" ]; then
          zip ../chuan-${GOOS}-${GOARCH}.zip ${BINARY_NAME}
        else
          tar -czf ../chuan-${GOOS}-${GOARCH}.tar.gz ${BINARY_NAME}
        fi
    
    - name: Upload artifacts
      uses: actions/upload-artifact@v3
      with:
        name: chuan-${{ matrix.goos }}-${{ matrix.goarch }}
        path: chuan-${{ matrix.goos }}-${{ matrix.goarch }}.*
        retention-days: 5

  release:
    name: Create Release
    runs-on: ubuntu-latest
    needs: build
    if: startsWith(github.ref, 'refs/tags/')
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
    
    - name: Download all artifacts
      uses: actions/download-artifact@v3
      with:
        path: artifacts
    
    - name: Prepare release files
      run: |
        mkdir -p release
        find artifacts -name "*.zip" -o -name "*.tar.gz" | xargs -I {} cp {} release/
        ls -la release/
    
    - name: Create Release
      uses: softprops/action-gh-release@v1
      with:
        files: release/*
        generate_release_notes: true
        draft: false
        prerelease: false
        body: |
          ## 🚀 川 P2P文件传输系统 ${{ github.ref_name }}
          
          ### 📦 下载说明
          - `chuan-linux-amd64.tar.gz` - Linux x64
          - `chuan-linux-arm64.tar.gz` - Linux ARM64
          - `chuan-darwin-amd64.tar.gz` - macOS Intel
          - `chuan-darwin-arm64.tar.gz` - macOS Apple Silicon
          - `chuan-windows-amd64.zip` - Windows x64
          
          ### 🏃‍♂️ 快速开始
          1. 下载对应平台的二进制文件
          2. 解压后运行 `./chuan` (Linux/macOS) 或 `chuan.exe` (Windows)
          3. 访问 http://localhost:8080 开始使用
          
          ### ✨ 主要功能
          - 🔄 P2P文件传输，无需服务器中转
          - 🎯 6位取件码，简单易用
          - 👥 多人房间支持
          - 📁 动态添加文件
          - 🚀 高速传输优化
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
