name: Release Core

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      tag_name:
        description: "Tag name for release"
        required: true
        type: string

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  build:
    name: Build for ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: macos-latest
            target: x86_64-apple-darwin
            name: ${{ github.event.repository.name }}-x86_64-apple-darwin.tar.gz
          - os: macos-latest
            target: aarch64-apple-darwin
            name: ${{ github.event.repository.name }}-aarch64-apple-darwin.tar.gz
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            name: ${{ github.event.repository.name }}-x86_64-unknown-linux-gnu.tar.gz
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            name: ${{ github.event.repository.name }}-x86_64-pc-windows-msvc.zip

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install system dependencies (Linux)
        if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install -y libasound2-dev pkg-config alsa-utils

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

      - name: Cache dependencies
        uses: Swatinem/rust-cache@v2

      - name: Build release
        run: cargo build --release --target ${{ matrix.target }}

      - name: Package binary (Unix)
        if: matrix.os != 'windows-latest'
        run: |
          cd target/${{ matrix.target }}/release
          tar -czf ../../../${{ matrix.name }} ${{ github.event.repository.name }}
          cd ../../..

      - name: Package binary (Windows)
        if: matrix.os == 'windows-latest'
        run: |
          cd target/${{ matrix.target }}/release
          7z a ../../../${{ matrix.name }} ${{ github.event.repository.name }}.exe
          cd ../../..

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: binaries-${{ matrix.target }}
          path: ${{ matrix.name }}

  create-release:
    name: Create GitHub Release
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Get version from tag
        id: get_version
        run: |
          echo "${{ github.event_name }}"
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            VERSION="${{ inputs.tag_name }}"
          else
            VERSION="${GITHUB_REF#refs/tags/}"
          fi
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "VERSION: $VERSION"

      - name: Create release archives
        run: |
          mkdir release-assets
          for dir in artifacts/*/; do
          if [ -d "$dir" ]; then
          mv "$dir"/*.tar.gz release-assets/ 2>/dev/null || true
          mv "$dir"/*.zip release-assets/ 2>/dev/null || true
          fi
          done
          ls -la release-assets/

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.get_version.outputs.version }}
          name: Release ${{ steps.get_version.outputs.version }}
          body: |
            ## Changes

             See [CHANGELOG.md](https://github.com/${{ github.event.repository.name }}/blob/main/CHANGELOG.md) for details.

             ## Downloads

             This release includes binaries for multiple platforms:
             - macOS (x86_64)
             - macOS (Apple Silicon)
             - Linux (x86_64)
             - Windows (x86_64)
          files: release-assets/*
          draft: false
          prerelease: false

  publish-crate:
    name: Publish to Crates.io
    needs: create-release
    runs-on: ubuntu-latest
    if: github.event.repository.fork == false
    environment: crates-io
    permissions:
      contents: read
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install system dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libasound2-dev pkg-config

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Get version
        id: get_version
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            VERSION="${{ github.event.inputs.tag_name }}"
          else
            VERSION="${{ github.ref_name }}"
          fi
          CLEAN_VERSION="${VERSION#v}"
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "clean_version=$CLEAN_VERSION" >> $GITHUB_OUTPUT

      - name: Update Cargo.toml version
        run: |
          sed -i 's|^version = ".*"|version = "${{ steps.get_version.outputs.clean_version }}"|' Cargo.toml

      - name: Cache dependencies
        uses: Swatinem/rust-cache@v2

      - name: Commit version change
        run: |
          git config user.name "GitHub Actions"
          git config user.email "actions@github.com"
          git add .
          git commit -m "Release version ${{ steps.get_version.outputs.version }}"

      - name: Verify crate can be published
        run: cargo publish --dry-run --allow-dirty

      - name: Publish crate
        run: cargo publish --token ${{ secrets.CRATES_IO_TOKEN }} --allow-dirty
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}

  create-choco-package:
    name: Publish to Chocolatey
    needs: create-release
    runs-on: windows-latest
    if: github.event.repository.fork == false
    environment: choco

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Get version from workflow run
        id: get_version
        shell: bash
        run: |
          # Get the tag from the triggering workflow
          TAG=$(curl -s "${{ github.event.workflow_run.artifacts_url }}" | jq -r '.artifacts[0].name' | sed 's/binaries-.*//')
          if [ -z "$TAG" ]; then
            # Fallback: get latest tag
            TAG=$(curl -s "https://api.github.com/repos/${{ github.event.repository.name }}/releases/latest" | jq -r '.tag_name')
          fi
          CLEAN_VERSION="${TAG#v}"
          echo "version=$TAG" >> $GITHUB_OUTPUT

  trigger-homebrew:
    name: Trigger Homebrew Release
    needs: create-release
    runs-on: ubuntu-latest
    if: github.event.repository.fork == false
    steps:
      - name: Trigger Homebrew workflow
        run: |
          curl -X POST \
          -H "Authorization: Bearer ${{ secrets.HOMEBREW_TAP_TOKEN }}" \
          -H "Accept: application/vnd.github.v3+json" \
          https://api.github.com/repos/isfopo/homebrew-tap/dispatches \
          -d '{
            "event_type": "homebrew-release",
            "client_payload": {
              "version": "${{ github.event.inputs.tag_name }}",
              "repo": "${{ github.event.repository.name }}",
              "run_id": "${{ github.run_id }}"
            }
          }'

  trigger-scoop:
    name: Trigger Scoop Release
    needs: create-release
    runs-on: ubuntu-latest
    if: github.event.repository.fork == false
    steps:
      - name: Trigger Scoop workflow
        run: |
          curl -X POST \
            -H "Authorization: token ${{ secrets.SCOOP_BUCKET_TOKEN }}" \
            -H "Accept: application/vnd.github.everest-preview+json" \
            -H "Content-Type: application/json" \
            https://api.github.com/repos/isfopo/scoop-bucket/dispatches \
            -d '{
              "event_type": "scoop-release",
              "client_payload": {
                "owner": "${{ github.event.repository.owner.login }}",
                "repo": "${{ github.event.repository.name }}",
                "version": "${{ github.event.inputs.tag_name }}",
                "run_id": "${{ github.run_id }}"
              }
            }'
