#!/bin/bash

# Directory containing YAML files
MATCH_DIR="match"

# Check if directory exists
if [ ! -d "$MATCH_DIR" ]; then
    echo "Error: Directory '$MATCH_DIR' not found!"
    exit 1
fi

# Temporary file to store all triggers
ALL_TRIGGERS=$(mktemp)

# Find all YAML files and extract triggers
echo "Scanning YAML files in $MATCH_DIR directory..."
for file in "$MATCH_DIR"/*.y*ml; do
    if [ -f "$file" ]; then
        echo "Processing file: $(basename "$file")"
        # Extract triggers using grep and sed
        # This looks for lines with "trigger:" and captures the value
        grep -E '^\s*-\s*trigger:' "$file" | sed 's/.*trigger:\s*"\([^"]*\)".*/\1/' >> "$ALL_TRIGGERS"
    fi
done

# Check if we found any triggers
if [ ! -s "$ALL_TRIGGERS" ]; then
    echo "No triggers found in YAML files. Check file format or directory."
    rm "$ALL_TRIGGERS"
    exit 1
fi

# Sort triggers and find duplicates
echo -e "\nChecking for duplicate triggers..."
DUPLICATES=$(sort "$ALL_TRIGGERS" | uniq -d)

# Display results
if [ -z "$DUPLICATES" ]; then
    echo "Success: All triggers are unique!"
    TOTAL=$(wc -l < "$ALL_TRIGGERS")
    echo "Total number of triggers found: $TOTAL"
else
    echo "Error: Duplicate triggers found:"
    echo "$DUPLICATES"

    # Optional: Show which files contain each duplicate
    echo -e "\nDuplicates found in these files:"
    for dupe in $DUPLICATES; do
        echo "Trigger \"$dupe\" found in:"
        grep -l "trigger: \"$dupe\"" "$MATCH_DIR"/*.y*ml
    done
fi

# Clean up
rm "$ALL_TRIGGERS"