# CodeCritical scan gate for GitHub Actions.
# Store the agent secret as the CODECRITICAL_API_KEY repository secret.
# Fabricate nothing: POSTs an archive, polls until terminal, gates on verdict.
name: CodeCritical Scan
on:
  push:
    branches: [main]

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Archive source
        run: git archive --format=zip --output=/tmp/source.zip HEAD

      - name: Submit scan
        env:
          CC_API_KEY: ${{ secrets.CODECRITICAL_API_KEY }}
          CC_HOST: https://codecritical.nemesisnet.co.za
        run: |
          JOB=$(curl -sf -X POST "$CC_HOST/api/v1/scan/upload" \
            -H "X-Api-Key: $CC_API_KEY" \
            -F "file=@/tmp/source.zip" | jq -r '.data.jobId')
          echo "job=$JOB" >> "$GITHUB_ENV"

          for i in $(seq 1 60); do
            STATUS=$(curl -sf "$CC_HOST/api/v1/scan/$JOB/status" \
              -H "X-Api-Key: $CC_API_KEY" | jq -r '.data.status')
            [[ "$STATUS" == "COMPLETED" || "$STATUS" == "FAILED" ]] && break
            sleep 10
          done
          [[ "$STATUS" == "COMPLETED" ]] || { echo "Scan did not complete"; exit 1; }

      - name: Fetch results
        env:
          CC_API_KEY: ${{ secrets.CODECRITICAL_API_KEY }}
          CC_HOST: https://codecritical.nemesisnet.co.za
        run: |
          curl -sf "$CC_HOST/api/v1/scan/$job" -H "X-Api-Key: $CC_API_KEY" \
            -o codecritical-result.json
          curl -sf "$CC_HOST/api/v1/scan/$job/export/md" \
            -H "X-Api-Key: $CC_API_KEY" -o codecritical-report.md

          python3 - <<'PY'
          import json, sys
          r = json.load(open("codecritical-result.json"))["data"]
          print(f"verdict={r.get('verdict')} score={r.get('nemesisScore')} "
                f"confidence={r.get('confidence')} skipped={r.get('enginesSkipped')}")
          if r.get("verdict") == "FAIL":
              sys.exit(1)   # gate the pipeline on a failing verdict
          PY

      - name: Upload report artifacts
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: codecritical-report
          path: |
            codecritical-result.json
            codecritical-report.md
