#!/bin/bash
set -e

BASE_BRANCH="$1"

if [ -z "$BASE_BRANCH" ]; then
  if [ -n "$SYSTEM_PULLREQUEST_TARGETBRANCH" ]; then
    BASE_BRANCH="${SYSTEM_PULLREQUEST_TARGETBRANCH#refs/heads/}"
  elif git rev-parse --verify "origin/master" >/dev/null 2>&1; then
    BASE_BRANCH="master"
  else
    BASE_BRANCH="main"
  fi
fi

echo "Filtering issues by Azure PR diff..."
echo "Base branch: $BASE_BRANCH"

if [ ! -f "sonar-results/issues.json" ]; then
  echo "sonar-results/issues.json not found"
  exit 1
fi

echo "Trying to fetch origin/$BASE_BRANCH..."
git fetch origin "$BASE_BRANCH" >/dev/null 2>&1 || \
  echo "Could not fetch origin/$BASE_BRANCH. Continuing with local refs."

CHANGED_FILES_FILE="$(mktemp)"
TMP_FILE="$(mktemp)"

if git rev-parse --verify "origin/$BASE_BRANCH" >/dev/null 2>&1; then
  git diff --name-only "origin/$BASE_BRANCH"...HEAD > "$CHANGED_FILES_FILE"
else
  echo "origin/$BASE_BRANCH not available. Skipping PR diff filter."
  cp sonar-results/issues.json "$TMP_FILE"
  mv "$TMP_FILE" sonar-results/issues.json
  echo "Issues count without PR diff filter:"
  jq 'length' sonar-results/issues.json
  exit 0
fi

echo "Changed files:"
cat "$CHANGED_FILES_FILE"

jq -R -s '
  split("\n")
  | map(select(length > 0))
' "$CHANGED_FILES_FILE" > "$CHANGED_FILES_FILE.json"

jq --slurpfile changed "$CHANGED_FILES_FILE.json" '
[
  .[]
  | select(
      (.component | split(":") | last) as $issueFile
      | ($changed[0] | index($issueFile))
    )
]
' sonar-results/issues.json > "$TMP_FILE"

mv "$TMP_FILE" sonar-results/issues.json

echo "Filtered issues count:"
jq 'length' sonar-results/issues.json