#!/bin/bash

# Script pour appliquer l'automation complète à tous les engines
# Usage: ./scripts/apply_full_automation.sh

set -euo pipefail

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

echo "🤖 Applying full automation to all Warfactory engines..."

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

# Template pour automation complète
AUTOMATION_TEMPLATE='# Apply comprehensive Warfactory automation
warfactory_add_full_automation(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 la ligne warfactory_add_defenses par automation complète
        sed -i "s|^warfactory_add_defenses.*|$AUTOMATION_TEMPLATE|" "$cmake_file"

        # Substituer le nom du target
        sed -i "s/ENGINE_NAME/$target_name/g" "$cmake_file"

        # Créer répertoires de test et benchmark si ils n'existent pas
        engine_dir="$PROJECT_ROOT/engines/$engine"

        mkdir -p "$engine_dir/tests"
        mkdir -p "$engine_dir/benchmarks"

        # Créer exemple de test si pas existant
        test_file="$engine_dir/tests/test_$target_name.cpp"
        if [[ ! -f "$test_file" ]]; then
            cat > "$test_file" << 'EOF'
#include <catch2/catch_test_macros.hpp>
#include <warfactory/contracts.hpp>

// Tests unitaires automatiques pour ENGINE_NAME
// Générés par Warfactory automation

TEST_CASE("ENGINE_NAME basic functionality", "[ENGINE_NAME]") {
    SECTION("Engine initialization") {
        // TODO: Test engine creation and initialization
        REQUIRE(true); // Placeholder
    }

    SECTION("Contract validation") {
        // Test des contracts Warfactory
        WARFACTORY_PROPERTY_FINITE_VALUES(42.0);
        REQUIRE(std::isfinite(42.0));
    }

    SECTION("Error handling") {
        // Test fail-fast patterns
        REQUIRE_NOTHROW(WARFACTORY_REQUIRE(true));
    }
}

TEST_CASE("ENGINE_NAME integration tests", "[ENGINE_NAME][integration]") {
    SECTION("Inter-engine communication") {
        // TODO: Test communication with other engines
        REQUIRE(true); // Placeholder
    }

    SECTION("Performance requirements") {
        // TODO: Test performance requirements
        REQUIRE(true); // Placeholder
    }
}

TEST_CASE("ENGINE_NAME property-based tests", "[ENGINE_NAME][property]") {
    SECTION("Conservation properties") {
        // Test des propriétés mathématiques
        double input = 100.0;
        double output = input * 0.9; // 10% loss exemple

        WARFACTORY_PROPERTY_FINITE_VALUES(input);
        WARFACTORY_PROPERTY_FINITE_VALUES(output);
        REQUIRE(output <= input); // Output never exceeds input
    }
}
EOF
            # Remplacer ENGINE_NAME par le vrai nom
            sed -i "s/ENGINE_NAME/$target_name/g" "$test_file"
        fi

        # Créer exemple de benchmark si pas existant
        bench_file="$engine_dir/benchmarks/bench_$target_name.cpp"
        if [[ ! -f "$bench_file" ]]; then
            cat > "$bench_file" << 'EOF'
#include <benchmark/benchmark.h>
#include <warfactory/contracts.hpp>

// Benchmarks automatiques pour ENGINE_NAME
// Générés par Warfactory automation

static void BM_ENGINE_NAME_BasicOperation(benchmark::State& state) {
    for (auto _ : state) {
        // TODO: Benchmark core operation
        WARFACTORY_PROPERTY_FINITE_VALUES(42.0);
        benchmark::DoNotOptimize(42.0);
    }
    state.SetComplexityN(state.range(0));
}

BENCHMARK(BM_ENGINE_NAME_BasicOperation)
    ->Range(8, 8<<10)
    ->Complexity(benchmark::oN);

static void BM_ENGINE_NAME_MemoryAllocation(benchmark::State& state) {
    for (auto _ : state) {
        // TODO: Benchmark memory operations
        std::vector<double> data(state.range(0));
        benchmark::DoNotOptimize(data);
    }
    state.SetBytesProcessed(int64_t(state.iterations()) *
                           int64_t(state.range(0)) * sizeof(double));
}

BENCHMARK(BM_ENGINE_NAME_MemoryAllocation)
    ->Range(1<<10, 1<<18)
    ->Unit(benchmark::kMillisecond);

BENCHMARK_MAIN();
EOF
            # Remplacer ENGINE_NAME par le vrai nom
            sed -i "s/ENGINE_NAME/$target_name/g" "$bench_file"
        fi

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

echo ""
echo "🤖 Full automation applied to all engines!"
echo ""
echo "📋 What was configured:"
echo "  ✓ FetchContent dependency management (Redis++, JSON, spdlog, Catch2)"
echo "  ✓ CTest integration with per-engine test suites"
echo "  ✓ Doxygen documentation generation"
echo "  ✓ Engine export/import system for inter-engine dependencies"
echo "  ✓ Multiple build configurations (Debug, Release, Testing, Profiling)"
echo "  ✓ Precompiled headers for faster compilation"
echo "  ✓ CPack packaging (DEB, RPM, NSIS, etc.)"
echo "  ✓ Automation targets for Claude Code workflow"
echo "  ✓ Test files and benchmark templates generated"
echo ""
echo "🚀 Usage examples:"
echo "  mkdir build && cd build"
echo ""
echo "  # Full automation build:"
echo "  cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON -DENABLE_BENCHMARKING=ON .."
echo "  make claude-workflow"
echo ""
echo "  # Testing build:"
echo "  cmake -DCMAKE_BUILD_TYPE=Testing .."
echo "  make test-all-engines"
echo ""
echo "  # Documentation:"
echo "  make docs-all"
echo ""
echo "  # Packaging:"
echo "  make package-all"
echo ""
echo "  # CI/CD simulation:"
echo "  make ci-simulation"