name: Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      tag:
        description: 'Tag to release (e.g. v1.2.3)'
        required: true

permissions:
  contents: write

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod

      - name: Test
        run: go test ./...

      - name: Lint
        run: go vet ./...

  release:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod

      - name: Build release binaries
        run: |
          VERSION="${{ github.event.inputs.tag || github.ref_name }}"
          mkdir -p dist
          for target in "linux/amd64" "linux/arm64" "darwin/amd64" "darwin/arm64" "windows/amd64"; do
            GOOS="${target%/*}"
            GOARCH="${target#*/}"
            EXT=""
            [ "$GOOS" = "windows" ] && EXT=".exe"
            BINARY="vecna-${GOOS}-${GOARCH}${EXT}"
            CGO_ENABLED=0 GOOS="$GOOS" GOARCH="$GOARCH" go build \
              -trimpath \
              -ldflags "-s -w -X main.version=${VERSION}" \
              -o "dist/${BINARY}" \
              ./cmd/vecna
            if [ "$GOOS" = "windows" ]; then
              zip -j "dist/vecna-${GOOS}-${GOARCH}.zip" "dist/${BINARY}"
            else
              tar -czf "dist/vecna-${GOOS}-${GOARCH}.tar.gz" -C dist "${BINARY}"
            fi
            echo "Built ${BINARY}"
          done

      - name: Generate checksums
        run: |
          cd dist
          sha256sum *.tar.gz *.zip > checksums.txt

      - name: Create release and upload assets
        run: |
          TAG="${{ github.event.inputs.tag || github.ref_name }}"

          PREV_TAG=$(git tag --sort=-version:refname | grep -v "^${TAG}$" | head -1)
          if [ -n "$PREV_TAG" ]; then
            RANGE="${PREV_TAG}..${TAG}"
          else
            RANGE="HEAD~20..HEAD"
          fi
          NOTES=$(git log "$RANGE" --pretty=format:"- %s" --no-merges)
          BODY="## What's changed"$'\n'"${NOTES}"

          gh release create "${TAG}" \
            --title "${TAG}" \
            --notes "${BODY}" \
            dist/*.tar.gz dist/*.zip dist/checksums.txt
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
