name: Test Headless Mode 🤖

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main, develop ]
  workflow_dispatch:  # Allow manual trigger

permissions:
  contents: read
  actions: read
  checks: write

jobs:
  test-headless:
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest]
        ghidra-version: ["12.0", "latest"]
      fail-fast: false  # Continue other tests if one fails

    name: Test on ${{ matrix.os }} / Ghidra ${{ matrix.ghidra-version }}
    runs-on: ${{ matrix.os }}

    steps:
    - name: Checkout code
      uses: actions/checkout@v6
      with:
        lfs: true

    - name: Set up Java 21
      uses: actions/setup-java@v5
      with:
        java-version: "21"
        distribution: "microsoft"

    - name: Set up Python 3.10
      uses: actions/setup-python@v6
      with:
        python-version: "3.10"

    - name: Install Ghidra ${{ matrix.ghidra-version }}
      uses: antoniovazquezblanco/setup-ghidra@v2.0.16
      with:
        version: ${{ matrix.ghidra-version }}
        auth_token: ${{ secrets.GITHUB_TOKEN }}

    - name: Setup Gradle
      uses: gradle/actions/setup-gradle@v5
      with:
        gradle-version: "8.14"

    - name: Build ReVa Extension
      run: gradle clean buildExtension --no-build-cache

    - name: Install ReVa Extension to Ghidra
      run: |
        EXTENSION_ZIP=$(ls -1 dist/*.zip | head -n 1)
        echo "Installing extension: $EXTENSION_ZIP"
        unzip -q "$EXTENSION_ZIP" -d "$GHIDRA_INSTALL_DIR/Ghidra/Extensions/"
        ls -la "$GHIDRA_INSTALL_DIR/Ghidra/Extensions/"

    - name: Install uv
      uses: astral-sh/setup-uv@v7
      with:
        enable-cache: true

    - name: Install Python dependencies
      run: uv sync --prerelease=allow

    - name: Install PyGhidra from local Ghidra
      run: |
        echo "GHIDRA_INSTALL_DIR: $GHIDRA_INSTALL_DIR"
        uv pip install "${GHIDRA_INSTALL_DIR}/Ghidra/Features/PyGhidra/pypkg"

    - name: Verify PyGhidra Installation
      run: |
        uv run python -c "import pyghidra; print(f'PyGhidra version: {pyghidra.__version__}')"
        echo "PyGhidra installed successfully"

    - name: Run Headless Integration Tests
      id: headless_test
      run: |
        echo "::group::Running headless integration tests"
        uv run pytest tests/ -v --timeout=180 --tb=short --junitxml=test-results.xml
        echo "::endgroup::"
      timeout-minutes: 30
      env:
        GHIDRA_INSTALL_DIR: ${{ env.GHIDRA_INSTALL_DIR }}

    - name: Upload test artifacts
      uses: actions/upload-artifact@v6
      if: always()
      with:
        name: headless-test-results-${{ matrix.os }}-ghidra-${{ matrix.ghidra-version }}
        path: |
          test-results.xml
          *.log
          .pytest_cache/
        if-no-files-found: ignore
