name: Release

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

env:
  GITEA_SERVER: https://git.warky.dev
  GITEA_REPO: wdevs/amcs

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

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.26'

      - name: Cache Go modules
        uses: actions/cache@v4
        with:
          path: |
            ~/.cache/go-build
            ~/go/pkg/mod
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-go-

      - name: Download dependencies
        run: go mod download

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'

      - name: Install pnpm
        run: npm install -g pnpm

      - name: Build UI
        run: |
          cd ui
          pnpm install --frozen-lockfile
          pnpm run build

      - name: Set build vars
        id: vars
        run: |
          TAG="${{ github.event.inputs.tag || github.ref_name }}"
          echo "VERSION=${TAG}" >> $GITHUB_OUTPUT
          echo "COMMIT=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
          echo "BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> $GITHUB_OUTPUT

      - name: Build release binaries
        run: |
          VERSION="${{ steps.vars.outputs.VERSION }}"
          COMMIT="${{ steps.vars.outputs.COMMIT }}"
          BUILD_DATE="${{ steps.vars.outputs.BUILD_DATE }}"
          LDFLAGS="-s -w -X git.warky.dev/wdevs/amcs/internal/buildinfo.Version=${VERSION} -X git.warky.dev/wdevs/amcs/internal/buildinfo.TagName=${VERSION} -X git.warky.dev/wdevs/amcs/internal/buildinfo.Commit=${COMMIT} -X git.warky.dev/wdevs/amcs/internal/buildinfo.BuildDate=${BUILD_DATE}"
          mkdir -p dist
          for BINARY in amcs-server amcs-cli; do
            CMD="./cmd/${BINARY}"
            for PLATFORM in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64; do
              OS="${PLATFORM%/*}"
              ARCH="${PLATFORM#*/}"
              EXT=""
              [ "$OS" = "windows" ] && EXT=".exe"
              OUTPUT="dist/${BINARY}-${OS}-${ARCH}${EXT}"
              echo "Building ${OUTPUT}..."
              GOOS=$OS GOARCH=$ARCH go build -ldflags "${LDFLAGS}" -o "${OUTPUT}" "${CMD}"
            done
          done
          cd dist && sha256sum * > checksums.txt && cd ..

      - name: Create Gitea Release
        id: create_release
        run: |
          export VERSION="${{ steps.vars.outputs.VERSION }}"
          BODY=$(python3 <<'PY'
          import json, subprocess, os
          version = os.environ['VERSION']
          commit = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], text=True).strip()
          body = f"## {version}\n\nBuilt from commit {commit}.\n\nSee `checksums.txt` to verify downloads."
          print(json.dumps({
              'tag_name': version,
              'name': version,
              'body': body,
              'draft': False,
              'prerelease': False,
          }))
          PY
          )
          RESPONSE=$(curl -fsS -X POST "${{ env.GITEA_SERVER }}/api/v1/repos/${{ env.GITEA_REPO }}/releases" \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d "$BODY")
          RELEASE_ID=$(printf '%s' "$RESPONSE" | python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')
          echo "RELEASE_ID=${RELEASE_ID}" >> $GITHUB_OUTPUT

      - name: Upload release assets
        run: |
          RELEASE_ID="${{ steps.create_release.outputs.RELEASE_ID }}"
          for f in dist/*; do
            name=$(basename "$f")
            echo "Uploading ${name}..."
            curl -fsS -X POST \
              "${{ env.GITEA_SERVER }}/api/v1/repos/${{ env.GITEA_REPO }}/releases/${RELEASE_ID}/assets?name=${name}" \
              -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
              -H "Content-Type: application/octet-stream" \
              --data-binary @"${f}"
          done
