name: Release

on:
  push:
    tags:
      - 'v*.*.*'
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to release (e.g., v0.1.0)'
        required: true
        type: string

env:
  CARGO_TERM_COLOR: always

jobs:
  # Create release and build binaries
  release:
    name: Release - ${{ matrix.platform.release_for }}
    strategy:
      fail-fast: false
      matrix:
        platform:
          - release_for: Linux-x86_64
            os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            bin: mermaid
            daemon_bin: mermaidd
            package_suffix: linux-x86_64
            name: mermaid-linux-x86_64.tar.gz
            command: build

          - release_for: Linux-aarch64
            os: ubuntu-latest
            target: aarch64-unknown-linux-gnu
            bin: mermaid
            daemon_bin: mermaidd
            package_suffix: linux-aarch64
            name: mermaid-linux-aarch64.tar.gz
            command: build

          - release_for: Windows-x86_64
            os: windows-latest
            target: x86_64-pc-windows-msvc
            bin: mermaid.exe
            daemon_bin: mermaidd.exe
            name: mermaid-windows-x86_64.zip
            command: build

          - release_for: macOS-x86_64
            os: macos-latest
            target: x86_64-apple-darwin
            bin: mermaid
            daemon_bin: mermaidd
            name: mermaid-macos-x86_64.tar.gz
            command: build

          - release_for: macOS-aarch64
            os: macos-latest
            target: aarch64-apple-darwin
            bin: mermaid
            daemon_bin: mermaidd
            name: mermaid-macos-aarch64.tar.gz
            command: build

    runs-on: ${{ matrix.platform.os }}
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0

      - name: Install Rust
        uses: dtolnay/rust-toolchain@67ef31d5b988238dd797d409d6f9574278e20537 # master
        with:
          toolchain: stable
          targets: ${{ matrix.platform.target }}

      - name: Cache cargo registry
        uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2

      # Install cross-compilation tools for Linux ARM64
      - name: Install cross-compilation tools
        if: matrix.platform.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu

      - name: Build binary
        shell: bash
        run: |
          if [ "${{ matrix.platform.target }}" = "aarch64-unknown-linux-gnu" ]; then
            export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
          fi
          cargo build --verbose --release --target ${{ matrix.platform.target }}

      - name: Package as archive (Linux/macOS)
        if: contains(matrix.platform.os, 'ubuntu') || contains(matrix.platform.os, 'macos')
        run: |
          cd target/${{ matrix.platform.target }}/release
          tar czvf ../../../${{ matrix.platform.name }} ${{ matrix.platform.bin }} ${{ matrix.platform.daemon_bin }}
          cd -

      - name: Package as ZIP (Windows)
        if: contains(matrix.platform.os, 'windows')
        run: |
          cd target/${{ matrix.platform.target }}/release
          7z a ../../../${{ matrix.platform.name }} ${{ matrix.platform.bin }} ${{ matrix.platform.daemon_bin }}
          cd -

      - name: Install Linux packaging tools
        if: contains(matrix.platform.os, 'ubuntu')
        run: |
          cargo install cargo-deb --locked
          cargo install cargo-generate-rpm --locked

      - name: Package Linux distro artifacts
        if: contains(matrix.platform.os, 'ubuntu')
        shell: bash
        run: |
          cargo deb --no-build --target ${{ matrix.platform.target }} --output mermaid-cli-${{ matrix.platform.package_suffix }}.deb
          cargo generate-rpm --target ${{ matrix.platform.target }} --output mermaid-cli-${{ matrix.platform.package_suffix }}.rpm

      - name: Upload artifacts
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: ${{ matrix.platform.name }}
          path: ${{ matrix.platform.name }}

      - name: Upload Linux distro artifacts
        if: contains(matrix.platform.os, 'ubuntu')
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: mermaid-packages-${{ matrix.platform.package_suffix }}
          path: |
            mermaid-cli-${{ matrix.platform.package_suffix }}.deb
            mermaid-cli-${{ matrix.platform.package_suffix }}.rpm

  # Create GitHub release and attach binaries
  publish:
    name: Publish Release
    needs: [release]
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0

      - name: Download artifacts
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
        with:
          path: ./artifacts

      - name: Generate changelog
        id: changelog
        run: |
          # Get the previous tag
          PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
          if [ -z "$PREV_TAG" ]; then
            echo "First release" > CHANGELOG.md
          else
            echo "## Changes since $PREV_TAG" > CHANGELOG.md
            git log $PREV_TAG..HEAD --pretty=format:"- %s" >> CHANGELOG.md
          fi

      - name: Generate SHA256 checksums
        run: |
          find artifacts -type f | while IFS= read -r f; do
            ( cd "$(dirname "$f")" && sha256sum "$(basename "$f")" )
          done | sort -k2 > SHA256SUMS
          cat SHA256SUMS

      - name: Create Release
        uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1
        with:
          files: |
            ./artifacts/**/*
            SHA256SUMS
          draft: false
          prerelease: false
          generate_release_notes: true
          body_path: CHANGELOG.md
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  # Optional: Publish to crates.io
  publish-crate:
    name: Publish to crates.io
    needs: [release]
    runs-on: ubuntu-latest
    # Only run if explicitly enabled (requires CARGO_REGISTRY_TOKEN secret)
    if: ${{ vars.PUBLISH_TO_CRATES_IO == 'true' }}
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0

      - name: Install Rust
        uses: dtolnay/rust-toolchain@67ef31d5b988238dd797d409d6f9574278e20537 # master
        with:
          toolchain: stable

      - name: Publish to crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: |
          # Publish the workspace library first, then the binary crate that
          # depends on it. Recent cargo waits for the dependency to appear on
          # the index before publishing the dependent crate.
          cargo publish -p mermaid-runtime
          cargo publish -p mermaid-cli

  # Bump the Homebrew tap + Scoop bucket to the new release. This is a no-op
  # until TAP_TOKEN is set — a PAT (Contents: read/write) on
  # noahsabaj/homebrew-mermaid and noahsabaj/scoop-mermaid. No other setup.
  publish-packages:
    name: Publish package managers
    needs: [publish]
    runs-on: ubuntu-latest
    steps:
      - name: Check for TAP_TOKEN
        id: gate
        env:
          TAP_TOKEN: ${{ secrets.TAP_TOKEN }}
        run: |
          if [ -n "$TAP_TOKEN" ]; then
            echo "enabled=true" >> "$GITHUB_OUTPUT"
          else
            echo "TAP_TOKEN not set — skipping Homebrew/Scoop bump."
            echo "enabled=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Resolve version + checksums
        if: steps.gate.outputs.enabled == 'true'
        id: rel
        run: |
          set -euo pipefail
          TAG="${{ github.event.inputs.version || github.ref_name }}"
          VERSION="${TAG#v}"
          curl -fsSL -o SHA256SUMS \
            "https://github.com/noahsabaj/mermaid-cli/releases/download/${TAG}/SHA256SUMS"
          h() { grep " mermaid-$1$" SHA256SUMS | awk '{print $1}'; }
          {
            echo "tag=$TAG"
            echo "version=$VERSION"
            echo "mac_arm=$(h macos-aarch64.tar.gz)"
            echo "mac_x86=$(h macos-x86_64.tar.gz)"
            echo "lin_arm=$(h linux-aarch64.tar.gz)"
            echo "lin_x86=$(h linux-x86_64.tar.gz)"
            echo "win_x86=$(h windows-x86_64.zip)"
          } >> "$GITHUB_OUTPUT"

      - name: Update Homebrew tap
        if: steps.gate.outputs.enabled == 'true'
        env:
          TAP_TOKEN: ${{ secrets.TAP_TOKEN }}
          TAG: ${{ steps.rel.outputs.tag }}
          VERSION: ${{ steps.rel.outputs.version }}
          MAC_ARM: ${{ steps.rel.outputs.mac_arm }}
          MAC_X86: ${{ steps.rel.outputs.mac_x86 }}
          LIN_ARM: ${{ steps.rel.outputs.lin_arm }}
          LIN_X86: ${{ steps.rel.outputs.lin_x86 }}
        run: |
          set -euo pipefail
          git clone "https://x-access-token:${TAP_TOKEN}@github.com/noahsabaj/homebrew-mermaid.git" tap
          cat > tap/Formula/mermaid.rb <<RUBY
          class Mermaid < Formula
            desc "Open-source, model-agnostic AI pair programmer for the terminal"
            homepage "https://github.com/noahsabaj/mermaid-cli"
            version "${VERSION}"
            license any_of: ["MIT", "Apache-2.0"]

            on_macos do
              on_arm do
                url "https://github.com/noahsabaj/mermaid-cli/releases/download/${TAG}/mermaid-macos-aarch64.tar.gz"
                sha256 "${MAC_ARM}"
              end
              on_intel do
                url "https://github.com/noahsabaj/mermaid-cli/releases/download/${TAG}/mermaid-macos-x86_64.tar.gz"
                sha256 "${MAC_X86}"
              end
            end

            on_linux do
              on_arm do
                url "https://github.com/noahsabaj/mermaid-cli/releases/download/${TAG}/mermaid-linux-aarch64.tar.gz"
                sha256 "${LIN_ARM}"
              end
              on_intel do
                url "https://github.com/noahsabaj/mermaid-cli/releases/download/${TAG}/mermaid-linux-x86_64.tar.gz"
                sha256 "${LIN_X86}"
              end
            end

            def install
              bin.install "mermaid"
              bin.install "mermaidd"
            end

            test do
              assert_match "Mermaid v#{version}", shell_output("#{bin}/mermaid version")
            end
          end
          RUBY
          cd tap
          if git diff --quiet; then echo "Homebrew tap already current"; exit 0; fi
          git -c user.name="github-actions[bot]" \
              -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
              commit -am "mermaid ${VERSION}"
          git push

      - name: Update Scoop bucket
        if: steps.gate.outputs.enabled == 'true'
        env:
          TAP_TOKEN: ${{ secrets.TAP_TOKEN }}
          TAG: ${{ steps.rel.outputs.tag }}
          VERSION: ${{ steps.rel.outputs.version }}
          WIN_X86: ${{ steps.rel.outputs.win_x86 }}
        run: |
          set -euo pipefail
          git clone "https://x-access-token:${TAP_TOKEN}@github.com/noahsabaj/scoop-mermaid.git" bucket
          cat > bucket/bucket/mermaid.json <<JSON
          {
              "version": "${VERSION}",
              "description": "Open-source, model-agnostic AI pair programmer for the terminal.",
              "homepage": "https://github.com/noahsabaj/mermaid-cli",
              "license": "MIT OR Apache-2.0",
              "architecture": {
                  "64bit": {
                      "url": "https://github.com/noahsabaj/mermaid-cli/releases/download/${TAG}/mermaid-windows-x86_64.zip",
                      "hash": "${WIN_X86}"
                  }
              },
              "bin": [
                  "mermaid.exe",
                  "mermaidd.exe"
              ],
              "checkver": {
                  "github": "https://github.com/noahsabaj/mermaid-cli"
              },
              "autoupdate": {
                  "architecture": {
                      "64bit": {
                          "url": "https://github.com/noahsabaj/mermaid-cli/releases/download/v\$version/mermaid-windows-x86_64.zip"
                      }
                  },
                  "hash": {
                      "url": "https://github.com/noahsabaj/mermaid-cli/releases/download/v\$version/SHA256SUMS"
                  }
              }
          }
          JSON
          cd bucket
          if git diff --quiet; then echo "Scoop bucket already current"; exit 0; fi
          git -c user.name="github-actions[bot]" \
              -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
              commit -am "mermaid ${VERSION}"
          git push

  # Bump the WinGet package (NoahSabaj.Mermaid) by opening a PR to
  # microsoft/winget-pkgs. No-op until WINGET_TOKEN is set — a *classic* PAT
  # with `public_repo` scope, owned by the account that holds the fork of
  # microsoft/winget-pkgs (fine-grained PATs are NOT supported by the action).
  # The action only *bumps* an existing package; the first version of
  # NoahSabaj.Mermaid is seeded manually once.
  publish-winget:
    name: Publish to WinGet
    needs: [publish]
    runs-on: ubuntu-latest
    steps:
      - name: Check for WINGET_TOKEN
        id: gate
        env:
          WINGET_TOKEN: ${{ secrets.WINGET_TOKEN }}
        run: |
          if [ -n "$WINGET_TOKEN" ]; then
            echo "enabled=true" >> "$GITHUB_OUTPUT"
          else
            echo "WINGET_TOKEN not set — skipping WinGet submission."
            echo "enabled=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Resolve version
        if: steps.gate.outputs.enabled == 'true'
        id: ver
        run: |
          TAG="${{ github.event.inputs.version || github.ref_name }}"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"
          echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"

      - name: Submit to WinGet
        if: steps.gate.outputs.enabled == 'true'
        # The action only *bumps* an existing winget-pkgs entry; until
        # NoahSabaj.Mermaid is seeded (microsoft/winget-pkgs#391817, pending
        # upstream review) this step fails. Tolerate it so the release run stays
        # green — it becomes a no-op once the seed lands and the bump succeeds.
        # Remove this line then.
        continue-on-error: true
        uses: vedantmgoyal9/winget-releaser@4ffc7888bffd451b357355dc214d43bb9f23917e # v2
        with:
          identifier: NoahSabaj.Mermaid
          version: ${{ steps.ver.outputs.version }}
          installers-regex: 'mermaid-windows-x86_64\.zip$'
          release-tag: ${{ steps.ver.outputs.tag }}
          fork-user: noahsabaj
          token: ${{ secrets.WINGET_TOKEN }}
