name: Build and Release

on:
  push:
    branches:
      - main
      - master
    tags:
      - 'v*'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        run: |
          cd $GITHUB_WORKSPACE
          git init
          git remote add origin ${{ github.server_url }}/${{ github.repository }}.git
          
          if [[ "${{ github.ref }}" == refs/tags/* ]]; then
            # For tags, fetch the specific tag and checkout the commit it points to
            git fetch origin ${{ github.ref }}:refs/tags/${{ github.ref_name }}
            git checkout refs/tags/${{ github.ref_name }}
          else
            # For branches, fetch and checkout with tracking
            git fetch origin ${{ github.ref_name }}:refs/remotes/origin/${{ github.ref_name }}
            git checkout -b ${{ github.ref_name }} origin/${{ github.ref_name }}
          fi

      - name: Set up Go
        run: |
          wget https://go.dev/dl/go1.24.4.linux-amd64.tar.gz
          tar -C /usr/local -xzf go1.24.4.linux-amd64.tar.gz
          export PATH=$PATH:/usr/local/go/bin
          go version

      - name: Generate version
        id: version
        run: |
          if [[ "${{ github.ref }}" == refs/tags/* ]]; then
            VERSION=${{ github.ref_name }}
          else
            VERSION=dev-${{ github.sha }}
          fi
          echo "version=${VERSION}" >> $GITHUB_ENV

      - name: Build all binaries
        run: |
          export PATH=$PATH:/usr/local/go/bin
          mkdir -p bin
          
          # Generate templ first
          go run github.com/a-h/templ/cmd/templ@latest generate
          
          # Linux AMD64
          echo "Building Linux AMD64..."
          GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o bin/nerd-monitor-server-linux-amd64 ./cmd/server
          GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o bin/nerd-monitor-agent-linux-amd64 ./cmd/agent
          
          # Linux ARM64
          echo "Building Linux ARM64..."
          GOOS=linux GOARCH=arm64 go build -ldflags="-w -s" -o bin/nerd-monitor-server-linux-arm64 ./cmd/server
          GOOS=linux GOARCH=arm64 go build -ldflags="-w -s" -o bin/nerd-monitor-agent-linux-arm64 ./cmd/agent
          
          # macOS AMD64
          echo "Building macOS AMD64..."
          GOOS=darwin GOARCH=amd64 go build -ldflags="-w -s" -o bin/nerd-monitor-server-darwin-amd64 ./cmd/server
          GOOS=darwin GOARCH=amd64 go build -ldflags="-w -s" -o bin/nerd-monitor-agent-darwin-amd64 ./cmd/agent
          
          # macOS ARM64
          echo "Building macOS ARM64..."
          GOOS=darwin GOARCH=arm64 go build -ldflags="-w -s" -o bin/nerd-monitor-server-darwin-arm64 ./cmd/server
          GOOS=darwin GOARCH=arm64 go build -ldflags="-w -s" -o bin/nerd-monitor-agent-darwin-arm64 ./cmd/agent
          
          # Windows AMD64
          echo "Building Windows AMD64..."
          GOOS=windows GOARCH=amd64 go build -ldflags="-w -s" -o bin/nerd-monitor-server-windows-amd64.exe ./cmd/server
          GOOS=windows GOARCH=amd64 go build -ldflags="-w -s" -o bin/nerd-monitor-agent-windows-amd64.exe ./cmd/agent
          
          echo "Build complete! Files:"
          ls -lh bin/

      - name: Create checksums
        run: |
          cd bin
          sha256sum * > SHA256SUMS
          cd ..
          echo "Checksums:"
          cat bin/SHA256SUMS

      - name: Create Release and Upload
        if: startsWith(github.ref, 'refs/tags/')
        run: |
          export GITEA_TOKEN="${{ secrets.GITEA_TOKEN }}"
          export GITEA_URL="${{ github.server_url }}"
          export REPO_OWNER="${{ github.repository_owner }}"
          export REPO_NAME="${{ github.repository }}"
          export REPO_NAME=${REPO_NAME#*/}
          
          TAG=${{ github.ref_name }}
          
          echo "Creating release for tag: $TAG"
          echo "Repository: $REPO_OWNER/$REPO_NAME"
          
          # Create release using Gitea API with wget
          echo "Creating new release..."
          
          # Create JSON payload in a temp file
          cat > /tmp/release.json << 'PAYLOAD'
          {"tag_name":"TAG_PLACEHOLDER","name":"Release TAG_PLACEHOLDER","draft":false,"prerelease":false}
          PAYLOAD
          sed -i "s/TAG_PLACEHOLDER/$TAG/g" /tmp/release.json
          
          RESPONSE=$(wget --post-file=/tmp/release.json \
            --header="Authorization: token $GITEA_TOKEN" \
            --header="Content-Type: application/json" \
            -O - -q \
            "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/releases")
          
          # Extract release ID using grep
          RELEASE_ID=$(echo "$RESPONSE" | grep -o '"id":[0-9]*' | head -1 | grep -o '[0-9]*')
          
          if [ -z "$RELEASE_ID" ]; then
            echo "Failed to create release. Response:"
            echo "$RESPONSE"
            exit 1
          fi
          
          echo "Created release ID: $RELEASE_ID"
          
          # Upload all binaries
          echo "Uploading release artifacts..."
          for file in bin/*; do
            if [ -f "$file" ]; then
              filename=$(basename "$file")
              echo "  Uploading: $filename"
              
              # Upload binary file to Gitea API
              UPLOAD_RESPONSE=$(wget --post-file="$file" \
                --header="Authorization: token $GITEA_TOKEN" \
                --header="Content-Type: application/octet-stream" \
                -O - -q \
                "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/releases/$RELEASE_ID/assets?name=$filename" 2>&1)
              
              if echo "$UPLOAD_RESPONSE" | grep -q '"id"'; then
                echo "    ✓ $filename uploaded"
              else
                echo "    ✗ Failed to upload $filename"
                echo "Response: $UPLOAD_RESPONSE"
              fi
            fi
          done
          
          echo ""
          echo "Release completed!"
          echo "View at: $GITEA_URL/$REPO_OWNER/$REPO_NAME/releases/tag/$TAG"
