#!/bin/bash
set -euo pipefail

JSON_FILE="${1:-scan_results.json}"
FAIL_ON_MED_OR_HIGH="${2:-true}"

if [[ ! -s "$JSON_FILE" ]]; then
  echo "[INFO] No scan results file present; nothing to evaluate."
  exit 0
fi

MED_PLUS=$(jq '[.[].findings] | flatten | map(select(.severity=="MEDIUM" or .severity=="HIGH" or .severity=="CRITICAL")) | length' "$JSON_FILE")
CRIT=$(jq '[.[].findings] | flatten | map(select(.severity=="CRITICAL")) | length' "$JSON_FILE")
HIGH=$(jq '[.[].findings] | flatten | map(select(.severity=="HIGH")) | length' "$JSON_FILE")
MED=$(jq '[.[].findings] | flatten | map(select(.severity=="MEDIUM")) | length' "$JSON_FILE")

echo "[INFO] Findings by severity => CRITICAL: ${CRIT}, HIGH: ${HIGH}, MEDIUM: ${MED}"

if [[ "${FAIL_ON_MED_OR_HIGH,,}" == "true" ]]; then
  if [[ "$MED_PLUS" -gt 0 ]]; then
    echo "[FAIL] Medium or higher findings detected (${MED_PLUS}). Failing the build as configured."
    exit 1
  fi
fi

echo "[OK] Quality gate passed."