#!/bin/bash

# Script pour appliquer les défenses Warfactory à tous les engines
# Usage: ./scripts/apply_defenses_to_all_engines.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "🛡️  Applying Warfactory defenses to all engines..."

# Liste des engines
ENGINES=(
    "Designer-Engine"
    "Event-Engine"
    "Factory-Engine"
    "Intelligence-Engine"
    "Logistic-Engine"
    "MacroEntity-Engine"
    "Map-Engine"
    "Operation-Engine"
    "War-Engine"
)

# Template pour les défenses
DEFENSE_TEMPLATE='# Apply comprehensive Warfactory defensive programming
warfactory_add_defenses(ENGINE_NAME)
warfactory_add_cppcheck(ENGINE_NAME)
warfactory_add_pvs_studio(ENGINE_NAME)
warfactory_add_property_testing(ENGINE_NAME)

# Engine-specific "No Trust" configuration'

for engine in "${ENGINES[@]}"; do
    echo "   Processing $engine..."

    # Nom du target (en minuscules avec tirets)
    target_name=$(echo "$engine" | tr '[:upper:]' '[:lower:]')

    cmake_file="$PROJECT_ROOT/engines/$engine/CMakeLists.txt"

    if [[ -f "$cmake_file" ]]; then
        # Remplacer le commentaire "Configuration \"No Trust\"" par notre template
        defense_block=$(echo "$DEFENSE_TEMPLATE" | sed "s/ENGINE_NAME/$target_name/g")

        # Utiliser sed pour remplacer la ligne de commentaire
        sed -i "s|# Configuration \"No Trust\" pour Claude Code|$defense_block|" "$cmake_file"

        echo "   ✓ $engine updated"
    else
        echo "   ⚠️  $cmake_file not found"
    fi
done

echo "🛡️  All engines updated with Warfactory defenses!"
echo ""
echo "Available build options:"
echo "  -DENABLE_STATIC_ANALYSIS=ON   : Enable Clang Static Analyzer"
echo "  -DENABLE_FUZZING=ON           : Enable fuzzing infrastructure"
echo "  -DCMAKE_BUILD_TYPE=Debug      : Enable all sanitizers"
echo ""
echo "Usage examples:"
echo "  mkdir build && cd build"
echo "  cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_STATIC_ANALYSIS=ON .."
echo "  make economy-engine"
echo "  make economy-engine_cppcheck  # Run static analysis"