#!/bin/bash

# Script to check for duplicate rule group names in rendered rule bundles.
# The check runs per generated rules file, matching how rendered bundles are
# validated and applied.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="${SCRIPT_DIR}/.."
GENERATED_RULES_ROOT="${PROJECT_ROOT}/newrules/prod"
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "${TEMP_DIR}"' EXIT

collect_target_paths() {
    if [ "$#" -gt 0 ]; then
        for target in "$@"; do
            case "${target}" in
                /*) printf '%s\n' "${target}" ;;
                *) printf '%s\n' "${PROJECT_ROOT}/${target}" ;;
            esac
        done
    else
        printf '%s\n' "${GENERATED_RULES_ROOT}"
    fi
}

extract_group_names() {
    local target_path

    for target_path in "$@"; do
        if [ -d "${target_path}" ]; then
            find "${target_path}" -type f \( -name "*.yaml" -o -name "*.yml" \) -print0
        elif [ -f "${target_path}" ]; then
            printf '%s\0' "${target_path}"
        fi
    done |
    while IFS= read -r -d '' file; do
        awk -v file="${file}" '
            /^[[:space:]]*-[[:space:]]*name:[[:space:]]*/ {
                group_name = $0
                sub(/^[[:space:]]*-[[:space:]]*name:[[:space:]]*/, "", group_name)
                if (group_name != "") {
                    printf "%s|%s\n", group_name, file
                }
            }
        ' "${file}"
    done
}

check_targets() {
    local has_duplicates=0
    local checked_files=0
    local temp_file
    local dup_file
    local target_path
    local file

    while IFS= read -r file; do
        [ -n "${file}" ] || continue
        checked_files=$((checked_files + 1))

        temp_file="${TEMP_DIR}/checked-${checked_files}.txt"
        dup_file="${TEMP_DIR}/checked-${checked_files}.dups"

        awk -v current_file="${file}" -F'|' '$2 == current_file { print $0 }' "${TEMP_DIR}/all-group-names.txt" > "${temp_file}"

        if [ ! -s "${temp_file}" ]; then
            continue
        fi

        cut -d'|' -f1 "${temp_file}" | sort | uniq -d > "${dup_file}"

        if [ -s "${dup_file}" ]; then
            has_duplicates=1
            echo "❌ Found duplicate rule group names in ${file#${PROJECT_ROOT}/}:"
            echo ""

            while IFS= read -r dup_name; do
                [ -n "${dup_name}" ] || continue
                echo "  Duplicate group name: '${dup_name}'"
            done < "${dup_file}"
            echo ""
        fi
    done < <(
        for target_path in "$@"; do
            if [ -d "${target_path}" ]; then
                find "${target_path}" -type f \( -name "*.yaml" -o -name "*.yml" \)
            elif [ -f "${target_path}" ]; then
                printf '%s\n' "${target_path}"
            fi
        done | sort -u
    )

    if [ "${checked_files}" -eq 0 ]; then
        echo "⚠️  No rule groups found in the generated rules"
        echo ""
        return 0
    fi

    if [ "${has_duplicates}" -eq 1 ]; then
        return 1
    fi

    echo "✅ No duplicate rule group names found in generated rules"
    echo "   Files checked: ${checked_files}"
    echo ""
    return 0
}

echo "🔍 Checking for duplicate rule group names in generated rules..."
echo ""

TARGET_PATHS=()
while IFS= read -r target_path; do
    TARGET_PATHS+=("${target_path}")
done < <(collect_target_paths "$@")

if [ "${#TARGET_PATHS[@]}" -eq 0 ]; then
    echo "⚠️  No generated rule paths found"
    exit 0
fi

for target_path in "${TARGET_PATHS[@]}"; do
    if [ ! -e "${target_path}" ]; then
        echo "⚠️  Skipping missing path: ${target_path#${PROJECT_ROOT}/}"
        echo ""
        exit 1
    fi
done

extract_group_names "${TARGET_PATHS[@]}" > "${TEMP_DIR}/all-group-names.txt"

if ! check_targets "${TARGET_PATHS[@]}"; then
    echo "❌ Rule check failed: Please rename duplicate groups in the affected rendered rule files."
    exit 1
fi

echo "✅ Duplicate rule group name check completed successfully."
exit 0
