name: Kuality Quality Gate

# Required secrets:
#   KUALITY_TOKEN  — your Kuality API key (from Organization → API Keys)
#
# Required/recommended variables (Settings → Variables):
#   KUALITY_API_URL    — https://kuality.io  (or your self-hosted URL)
#   STAGING_URL        — e.g. https://staging.yoursite.com
#   SCAN_TYPES         — comma-separated, e.g. "a11y,webvitals,headers"  (default: all)
#   SCORE_THRESHOLD    — minimum score to pass gate  (default: 70)
#   MAX_HIGH_FINDINGS  — maximum allowed high-severity findings  (default: 0)

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]

jobs:
  kuality-scan:
    name: Kuality quality gate
    runs-on: ubuntu-latest

    steps:
      - name: Trigger Kuality quality gate scan
        id: gate
        env:
          KUALITY_TOKEN: ${{ secrets.KUALITY_TOKEN }}
          KUALITY_API_URL: ${{ vars.KUALITY_API_URL || 'https://kuality.io' }}
          STAGING_URL: ${{ vars.STAGING_URL }}
          SCAN_TYPES: ${{ vars.SCAN_TYPES || '' }}
          SCORE_THRESHOLD: ${{ vars.SCORE_THRESHOLD || 70 }}
          MAX_HIGH: ${{ vars.MAX_HIGH_FINDINGS || 0 }}
        run: |
          set -euo pipefail

          BODY=$(jq -n \
            --arg target "$STAGING_URL" \
            --argjson threshold "$SCORE_THRESHOLD" \
            --argjson max_high "$MAX_HIGH" \
            --arg scan_types "$SCAN_TYPES" \
            '{
              target: $target,
              score_threshold: $threshold,
              max_high: $max_high
            } + (if $scan_types != "" then {scan_types: ($scan_types | split(","))} else {} end)'
          )

          HTTP_CODE=$(curl -s -o /tmp/gate_response.json -w "%{http_code}" \
            -X POST "$KUALITY_API_URL/api/v1/gates/evaluate" \
            -H "Authorization: Bearer $KUALITY_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$BODY")

          cat /tmp/gate_response.json | jq .

          PASSED=$(cat /tmp/gate_response.json | jq -r '.passed')
          SCORE=$(cat /tmp/gate_response.json | jq -r '.overall_score // "n/a"')

          echo "gate_passed=$PASSED" >> $GITHUB_OUTPUT
          echo "overall_score=$SCORE" >> $GITHUB_OUTPUT
          echo "http_code=$HTTP_CODE" >> $GITHUB_OUTPUT

          if [ "$HTTP_CODE" = "422" ] || [ "$PASSED" = "false" ]; then
            echo "::error title=Kuality Quality Gate Failed::Score: $SCORE — one or more checks did not meet thresholds. See gate details above."
            exit 1
          fi

          echo "::notice title=Kuality Quality Gate Passed::Score: $SCORE — all checks passed."

      - name: Download JUnit XML report
        if: always()
        env:
          KUALITY_TOKEN: ${{ secrets.KUALITY_TOKEN }}
          KUALITY_API_URL: ${{ vars.KUALITY_API_URL || 'https://kuality.io' }}
          STAGING_URL: ${{ vars.STAGING_URL }}
        run: |
          set -euo pipefail
          mkdir -p kuality-reports

          # Fetch the latest report ID for this target
          REPORTS=$(curl -sf "$KUALITY_API_URL/api/v1/reports?target=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$STAGING_URL'))")&limit=5" \
            -H "Authorization: Bearer $KUALITY_TOKEN")

          REPORT_ID=$(echo "$REPORTS" | jq -r '.[0].id // empty')

          if [ -n "$REPORT_ID" ]; then
            curl -sf "$KUALITY_API_URL/api/v1/reports/$REPORT_ID/junit" \
              -H "Authorization: Bearer $KUALITY_TOKEN" \
              -o kuality-reports/kuality-report.xml
            echo "JUnit report saved to kuality-reports/kuality-report.xml"
          else
            echo "No completed report found for $STAGING_URL — skipping JUnit download"
          fi

      - name: Publish JUnit test results
        uses: mikepenz/action-junit-report@v4
        if: always()
        with:
          report_paths: 'kuality-reports/*.xml'
          check_name: 'Kuality Quality Report'
          fail_on_failure: false
          include_passed: true

      - name: Upload Kuality reports
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: kuality-reports
          path: kuality-reports/
          retention-days: 14
