name: Test Coverage Check

on:
  pull_request:
    types: [labeled]

jobs:
  test:
    name: run tests and display coverage

    if: github.base_ref == 'main' && github.event.label.name == 'run-coverage-tests'

    runs-on: ubuntu-latest

    permissions:
      pull-requests: write
      contents: write

    env:
      SHOPIFY_FIXED_ARGS: ${{ secrets.SHOPIFY_FIXED_ARGS }}
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      MIN_COVERAGE_THRESHOLD: '99.0'

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

      - name: Set up Python 3.10
        uses: actions/setup-python@v4
        with:
          python-version: '3.10'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -e '.[milvus,shopify,hubspot]' --quiet

      - name: Run tests and check coverage threshold
        run: |
          # Run tests with coverage and generate all reports
          pytest tests/ --cov=arklex --cov-report=term-missing --cov-report=html --cov-report=xml --no-cov-on-fail
          
          # Extract coverage percentage from the XML report
          python -c "
          import xml.etree.ElementTree as ET
          import os
          
          try:
              tree = ET.parse('coverage.xml')
              root = tree.getroot()
              coverage = float(root.attrib['line-rate']) * 100
              print(f'Coverage: {coverage:.1f}%')
              
              # Get minimum coverage threshold from environment variable
              min_coverage = float(os.environ.get('MIN_COVERAGE_THRESHOLD', '99.0'))
              print(f'Minimum coverage threshold: {min_coverage}%')
              
              if coverage < min_coverage:
                  print(f'❌ Coverage ({coverage:.1f}%) is below minimum threshold ({min_coverage}%)')
                  print('This PR will be blocked until coverage is improved.')
                  exit(1)
              else:
                  print(f'✅ Coverage ({coverage:.1f}%) meets minimum threshold ({min_coverage}%)')
          except Exception as e:
              print(f'Error reading coverage data: {e}')
              print('❌ Could not determine coverage. Please check the test output.')
              exit(1)
          "

      - name: Upload coverage report
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: coverage.xml

      - name: Upload HTML coverage report
        uses: actions/upload-artifact@v4
        with:
          name: htmlcov
          path: htmlcov/

      - name: Display coverage
        uses: py-cov-action/python-coverage-comment-action@v3
        with:
          GITHUB_TOKEN: ${{ github.token }}
          MINIMUM_GREEN: 99.0
          MINIMUM_ORANGE: 70
