name: Release

on:
  push:
    tags:
      - '[0-9]*.[0-9]*.[0-9]*'
  workflow_dispatch:

concurrency:
  group: release-${{ github.ref }}
  cancel-in-progress: false

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: "1"
  CARGO_INCREMENTAL: "0"
  ZSTD_NBTHREADS: "0"
  CARGO_NET_GIT_FETCH_WITH_CLI: "true"

jobs:
  # ==========================================================================
  # validate-version — tag must match Cargo.toml version
  # ==========================================================================
  validate-version:
    name: Validate tag matches Cargo.toml
    runs-on: brefwiz
    steps:
      - uses: actions/checkout@v4
      - name: Check version consistency
        run: |
          CARGO_VERSION=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
          if [ "${{ github.ref_type }}" = "tag" ]; then
            TAG="${{ github.ref_name }}"
            if [ "$TAG" != "$CARGO_VERSION" ]; then
              echo "::error::Tag '$TAG' does not match Cargo.toml version '$CARGO_VERSION'"
              exit 1
            fi
          fi
          echo "Version: $CARGO_VERSION"

  # ==========================================================================
  # lint
  # ==========================================================================
  lint:
    name: Code Quality (Format + Clippy)
    needs: [validate-version]
    runs-on: brefwiz
    container:
      image: harbor.brefwiz.com/brefwiz/ci:latest
      options: --user root -v /var/cache/sccache:/var/cache/sccache
      credentials:
        username: ${{ secrets.HARBOR_USER }}
        password: ${{ secrets.HARBOR_TOKEN }}
    env:
      RUSTC_WRAPPER: sccache
      CARGO_REGISTRIES_BREFWIZ_TOKEN: "Bearer ${{ secrets.PACKAGE_READER_TOKEN || secrets.PACKAGE_PUBLISHER_TOKEN }}"
    steps:
      - uses: actions/checkout@v4
      - uses: actions/checkout@v4
        with:
          repository: brefwiz/ci-workflows
          ref: main
          path: .ci-workflows
          token: ${{ secrets.PACKAGE_READER_TOKEN || secrets.PACKAGE_PUBLISHER_TOKEN }}
      - uses: ./.ci-workflows/.gitea/actions/fmt
        with:
          checkout: "false"
      - uses: ./.ci-workflows/.gitea/actions/clippy
        with:
          checkout: "false"

  # ==========================================================================
  # security-audit
  # ==========================================================================
  security-audit:
    name: Security Audit
    needs: [validate-version]
    runs-on: brefwiz
    container:
      image: harbor.brefwiz.com/brefwiz/ci:latest
      options: --user root
      credentials:
        username: ${{ secrets.HARBOR_USER }}
        password: ${{ secrets.HARBOR_TOKEN }}
    env:
      CARGO_REGISTRIES_BREFWIZ_TOKEN: "Bearer ${{ secrets.PACKAGE_READER_TOKEN || secrets.PACKAGE_PUBLISHER_TOKEN }}"
    steps:
      - uses: actions/checkout@v4
      - uses: actions/checkout@v4
        with:
          repository: brefwiz/ci-workflows
          ref: main
          path: .ci-workflows
          token: ${{ secrets.PACKAGE_READER_TOKEN || secrets.PACKAGE_PUBLISHER_TOKEN }}
      - uses: ./.ci-workflows/.gitea/actions/audit
        with:
          checkout: "false"
          policies-token: ${{ secrets.PACKAGE_READER_TOKEN || secrets.PACKAGE_PUBLISHER_TOKEN }}

  # ==========================================================================
  # test
  # ==========================================================================
  test:
    name: Test Suite
    needs: [validate-version]
    runs-on: brefwiz
    container:
      image: harbor.brefwiz.com/brefwiz/ci:latest
      options: --user root -v /var/cache/sccache:/var/cache/sccache
      credentials:
        username: ${{ secrets.HARBOR_USER }}
        password: ${{ secrets.HARBOR_TOKEN }}
    env:
      RUSTC_WRAPPER: sccache
      CARGO_REGISTRIES_BREFWIZ_TOKEN: "Bearer ${{ secrets.PACKAGE_READER_TOKEN || secrets.PACKAGE_PUBLISHER_TOKEN }}"
    steps:
      - uses: actions/checkout@v4
      - uses: actions/checkout@v4
        with:
          repository: brefwiz/ci-workflows
          ref: main
          path: .ci-workflows
          token: ${{ secrets.PACKAGE_READER_TOKEN || secrets.PACKAGE_PUBLISHER_TOKEN }}
      - uses: ./.ci-workflows/.gitea/actions/coverage
        with:
          checkout: "false"

  # ==========================================================================
  # cargo-publish — publish crate to brefwiz Cargo registry
  # ==========================================================================
  cargo-publish:
    name: Publish to brefwiz Cargo registry
    needs: [lint, security-audit, test]
    runs-on: brefwiz
    container:
      image: harbor.brefwiz.com/brefwiz/ci:latest
      options: --user root
      credentials:
        username: ${{ secrets.HARBOR_USER }}
        password: ${{ secrets.HARBOR_TOKEN }}
    env:
      CARGO_REGISTRIES_BREFWIZ_TOKEN: "Bearer ${{ secrets.PACKAGE_PUBLISHER_TOKEN }}"
    steps:
      - uses: actions/checkout@v4
      - name: Publish groundwork
        run: |
          if ! cargo publish --registry brefwiz --token "Bearer ${{ secrets.PACKAGE_PUBLISHER_TOKEN }}" 2>&1 | tee /tmp/publish.log; then
            if grep -q "already uploaded\|already exists" /tmp/publish.log; then
              echo "Warning: Crate already published at this version (skipping)"
              exit 0
            fi
            cat /tmp/publish.log
            exit 1
          fi
          VERSION=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
          echo "✅ Published groundwork v${VERSION}" >> $GITHUB_STEP_SUMMARY

  # ==========================================================================
  # gitea-release — create release with changelog from git log
  # ==========================================================================
  gitea-release:
    name: Create Gitea Release
    needs: [cargo-publish]
    runs-on: brefwiz
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Create release
        env:
          GITEA_TOKEN: ${{ secrets.PACKAGE_PUBLISHER_TOKEN }}
        run: |
          VERSION=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
          TAG_NAME="${VERSION}"
          # grep exits 1 when no match; || true prevents pipefail from killing the step
          PREV_TAG=$(git tag --sort=-version:refname | grep -v "^${TAG_NAME}$" | head -1 || true)
          if [ -n "$PREV_TAG" ]; then
            CHANGELOG=$(git log "${PREV_TAG}..${TAG_NAME}" --pretty=format:"- %s" --no-merges)
          else
            CHANGELOG=$(git log --pretty=format:"- %s" --no-merges | head -20)
          fi
          # jq -Rs . encodes stdin as a JSON string — no python3 dependency
          CHANGELOG_JSON=$(printf '%s' "${CHANGELOG}" | jq -Rs .)
          printf '{"tag_name":"%s","name":"v%s","body":%s,"draft":false,"prerelease":false}' \
            "${TAG_NAME}" "${VERSION}" "${CHANGELOG_JSON}" | \
          curl -sf -X POST \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/json" \
            "${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/releases" \
            -d @-
          echo "✅ Released v${VERSION}" >> $GITHUB_STEP_SUMMARY
