#!/bin/bash
# Cleanup script for deprecated attribute rules
# Generated by GPT-5 analysis
# Execute deletions in descending line order to keep line numbers stable

set -e  # Exit on error

GRAMMAR_FILE="grammar.js"

echo "=== Starting cleanup of deprecated attribute rules ==="
echo "Backup current grammar.js..."
cp "$GRAMMAR_FILE" "${GRAMMAR_FILE}.before-cleanup"

echo ""
echo "Step 1: Remove preproc_attributed_split_procedure (lines 5571-5597)"
sed -i '5571,5597d' "$GRAMMAR_FILE"

echo "Step 2: Remove attribute_list (line 5451)"
sed -i '5451d' "$GRAMMAR_FILE"

echo "Step 3: Remove attributed_variable_declaration (lines 4311-4314)"
sed -i '4311,4314d' "$GRAMMAR_FILE"

echo "Step 4: Replace _var_declaration_with_optional_attribute (lines 4304-4308)"
sed -i '4304,4308c\    _var_declaration_with_optional_attribute: $ => $.variable_declaration,' "$GRAMMAR_FILE"

echo "Step 5: Remove attributed_interface_procedure (lines 2304-2307)"
sed -i '2304,2307d' "$GRAMMAR_FILE"

echo "Step 6: Remove attributed_controladdin_procedure (lines 2253-2257)"
sed -i '2253,2257d' "$GRAMMAR_FILE"

echo "Step 7: Remove attributed_onrun_trigger (lines 2053-2056)"
sed -i '2053,2056d' "$GRAMMAR_FILE"

echo "Step 8: Remove attributed_trigger (lines 2048-2051)"
sed -i '2048,2051d' "$GRAMMAR_FILE"

echo "Step 9: Remove attributed_procedure (lines 2024-2046)"
sed -i '2024,2046d' "$GRAMMAR_FILE"

echo "Step 10: Remove preproc_conditional_attributes (lines 2014-2022)"
sed -i '2014,2022d' "$GRAMMAR_FILE"

echo ""
echo "Step 11: Remove conflicts array entries"
sed -i '/\[\$\.preproc_split_procedure, \$\.preproc_attributed_split_procedure\],/d' "$GRAMMAR_FILE"
sed -i '/\[\$\.attributed_procedure, \$\.preproc_conditional_variables\],/d' "$GRAMMAR_FILE"

echo ""
echo "=== Cleanup complete ==="
echo "Lines removed: ~70 lines of deprecated code"
echo ""
echo "Verifying grammar loads..."
tree-sitter generate

if [ $? -eq 0 ]; then
    echo "✅ Grammar generates successfully!"
    wc -l "$GRAMMAR_FILE"
else
    echo "❌ Grammar generation failed - restoring backup"
    cp "${GRAMMAR_FILE}.before-cleanup" "$GRAMMAR_FILE"
    exit 1
fi
