#!/usr/bin/env bash
# Detect duplicate variable definitions in Pine Script files.
# Exits 1 and prints offending names+lines if duplicates are found.
# Usage: check_pine_duplicates.sh [file ...]
#   Defaults to strategies/*.pine if no args given.

set -euo pipefail

files=("${@:-strategies/*.pine}")
found=0

for f in "${files[@]}"; do
    [[ -f "$f" ]] || continue

    # Extract top-level assignments: lines that start with optional type + identifier + =
    # Captures: varname -> line numbers list
    declare -A first_line
    declare -A all_lines
    unset first_line all_lines
    declare -A first_line
    declare -A all_lines

    mapfile -t lines < "$f"
    lineno=0
    for line in "${lines[@]}"; do
        ((lineno++))
        # Match: optional "float/int/bool/string/color/label/line/array" then identifier then = (not ==)
        if [[ "$line" =~ ^[[:space:]]*(float|int|bool|string|color|label|line|array)?[[:space:]]*([a-zA-Z_][a-zA-Z0-9_]*)[[:space:]]*=[^=] ]]; then
            varname="${BASH_REMATCH[2]}"
            # Skip Pine keywords / single-char throwaways
            [[ "$varname" =~ ^(if|for|while|switch|var|varip|true|false|na|_)$ ]] && continue
            if [[ -n "${first_line[$varname]+x}" ]]; then
                if [[ "$found" -eq 0 ]]; then
                    echo "❌ Duplicate variable definitions found in: $f"
                fi
                echo "   '$varname' first defined at line ${first_line[$varname]}, redefined at line $lineno"
                found=1
            else
                first_line[$varname]=$lineno
            fi
        fi
    done
done

if [[ "$found" -ne 0 ]]; then
    echo ""
    echo "Fix: remove or rename the later definition(s) listed above."
    exit 1
fi

echo "✅ No duplicate variable definitions found in Pine files."
