name: Rust CLI Build

on:
  workflow_call:
  push:
    branches: [ main, feat/rust-cli ]
    paths:
      - 'crates/**'
      - 'Cargo.toml'
      - '.github/workflows/rust-cli.yml'
    tags:
      - 'cli@*'  # Trigger release on tags starting with cli@
  pull_request:
    branches: [ main ]
    paths:
      - 'crates/**'
      - 'Cargo.toml'
      - '.github/workflows/rust-cli.yml'

jobs:
  build:
    name: Build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-24.04
            target: x86_64-unknown-linux-gnu
            artifact_name: ov-linux-x86_64
          - os: ubuntu-24.04
            target: aarch64-unknown-linux-gnu
            artifact_name: ov-linux-aarch64
          - os: macos-15-intel
            target: x86_64-apple-darwin
            artifact_name: ov-macos-x86_64
          - os: macos-14
            target: aarch64-apple-darwin
            artifact_name: ov-macos-aarch64
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            artifact_name: ov-windows-x86_64.exe

    steps:
    - uses: actions/checkout@v6

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

    - name: Install system dependencies (Linux)
      if: runner.os == 'Linux'
      run: |
        sudo apt-get update
        sudo apt-get install -y pkg-config libssl-dev

    - name: Install cross-compilation tools (Linux ARM64)
      if: matrix.target == 'aarch64-unknown-linux-gnu'
      run: |
        sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
        echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> $GITHUB_ENV
        echo "CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc" >> $GITHUB_ENV
        echo "CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++" >> $GITHUB_ENV

    - name: Cache Cargo registry and index
      uses: actions/cache@v5
      with:
        path: |
          ~/.cargo/registry/index
          ~/.cargo/registry/cache
          ~/.cargo/git/db
        key: ${{ runner.os }}-cargo-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
        restore-keys: |
          ${{ runner.os }}-cargo-${{ matrix.target }}-
          ${{ runner.os }}-cargo-

    - name: Cache build artifacts
      uses: actions/cache@v5
      with:
        path: target
        key: ${{ runner.os }}-target-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}-${{ hashFiles('crates/**/*.rs') }}
        restore-keys: |
          ${{ runner.os }}-target-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}-
          ${{ runner.os }}-target-${{ matrix.target }}-

    - name: Build CLI
      run: cargo build --release --target ${{ matrix.target }} -p ov_cli
        
    - name: Create compressed artifacts
      shell: bash
      run: |
        mkdir -p artifacts
        cd target/${{ matrix.target }}/release

        if [[ "${{ matrix.os }}" == "windows-latest" ]]; then
          # Windows: create zip
          7z a ../../../artifacts/${{ matrix.artifact_name }}.zip ov.exe
          cd ../../../artifacts
          # Use PowerShell to get hash in correct format
          powershell -Command "(Get-FileHash -Algorithm SHA256 '${{ matrix.artifact_name }}.zip').Hash.ToLower() + '  ${{ matrix.artifact_name }}.zip'" > ${{ matrix.artifact_name }}.zip.sha256
        else
          # Unix: create tar.gz
          tar czf ../../../artifacts/${{ matrix.artifact_name }}.tar.gz ov
          cd ../../../artifacts
          # shasum format: <hash>  <filename>
          shasum -a 256 ${{ matrix.artifact_name }}.tar.gz > ${{ matrix.artifact_name }}.tar.gz.sha256
        fi

    - name: Verify checksum format
      shell: bash
      run: |
        echo "Contents of checksum file:"
        cat artifacts/*.sha256
        echo ""
        echo "Verifying checksum locally:"
        cd artifacts
        if [[ "${{ matrix.os }}" == "windows-latest" ]]; then
          sha256sum -c *.sha256 || shasum -a 256 -c *.sha256 || echo "Checksum verification skipped on Windows"
        else
          shasum -a 256 -c *.sha256
        fi

    - name: Upload artifacts
      uses: actions/upload-artifact@v7
      with:
        name: ${{ matrix.artifact_name }}
        path: artifacts/*

  release:
    name: Create GitHub Release
    runs-on: ubuntu-24.04
    needs: build
    if: startsWith(github.ref, 'refs/tags/cli@')
    permissions:
      contents: write
    steps:
    - name: Checkout code
      uses: actions/checkout@v6

    - name: Get version from tag
      id: get_version
      run: echo "version=${GITHUB_REF#refs/tags/cli@}" >> $GITHUB_OUTPUT

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

    - name: Display artifact structure
      run: ls -R artifacts/

    - name: Create GitHub Release
      uses: softprops/action-gh-release@v2
      with:
        name: CLI v${{ steps.get_version.outputs.version }}
        body: |
          # OpenViking CLI v${{ steps.get_version.outputs.version }}

          ## Installation

          ### Quick Install (macOS/Linux)
          ```bash
          curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/refs/tags/cli@${{ steps.get_version.outputs.version }}/crates/ov_cli/install.sh | bash
          ```

          ### Manual Installation
          Download the appropriate binary for your platform below, extract it, and add it to your PATH.

          The CLI command is simply `ov`:
          ```bash
          # After extraction
          chmod +x ov  # Unix only
          mv ov /usr/local/bin/  # or any directory in your PATH

          # Verify installation
          ov --version
          ```

          ### Checksums
          SHA256 checksums are provided for each binary for verification.

          ## Changes
          See the [commit history](https://github.com/${{ github.repository }}/commits/cli@${{ steps.get_version.outputs.version }}) for details.
        files: |
          artifacts/**/*.tar.gz
          artifacts/**/*.zip
          artifacts/**/*.sha256
        draft: false
        prerelease: ${{ contains(steps.get_version.outputs.version, 'alpha') || contains(steps.get_version.outputs.version, 'beta') || contains(steps.get_version.outputs.version, 'rc') }}
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
