#!/bin/bash
# Build script for Webpage Quality Analyzer C++ bindings

set -e  # Exit on error

echo "=== Building Webpage Quality Analyzer C++ Bindings ==="
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if cargo is available
if ! command -v cargo &> /dev/null; then
    echo -e "${RED}Error: Cargo not found. Please install Rust.${NC}"
    exit 1
fi

# Check if cmake is available
if ! command -v cmake &> /dev/null; then
    echo -e "${RED}Error: CMake not found. Please install CMake 3.15+.${NC}"
    exit 1
fi

# Step 1: Build Rust library with FFI feature
echo -e "${YELLOW}[1/4] Building Rust library with FFI feature...${NC}"
cargo build --release --features ffi
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Rust library built successfully${NC}"
else
    echo -e "${RED}✗ Rust library build failed${NC}"
    exit 1
fi
echo ""

# Check if library was generated
if [ ! -f "target/release/libwebpage_quality_analyzer.a" ]; then
    echo -e "${RED}Error: Static library not found at target/release/libwebpage_quality_analyzer.a${NC}"
    exit 1
fi

# Step 2: Create build directory
echo -e "${YELLOW}[2/4] Creating build directory...${NC}"
mkdir -p build
cd build
echo -e "${GREEN}✓ Build directory ready${NC}"
echo ""

# Step 3: Configure with CMake
echo -e "${YELLOW}[3/4] Configuring with CMake...${NC}"
cmake .. \
    -DCMAKE_BUILD_TYPE=Release \
    -DBUILD_EXAMPLES=ON \
    -DBUILD_TESTS=OFF
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ CMake configuration successful${NC}"
else
    echo -e "${RED}✗ CMake configuration failed${NC}"
    exit 1
fi
echo ""

# Step 4: Build C++ examples
echo -e "${YELLOW}[4/4] Building C++ examples...${NC}"
cmake --build . --config Release
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ C++ examples built successfully${NC}"
else
    echo -e "${RED}✗ C++ build failed${NC}"
    exit 1
fi
echo ""

# Summary
echo "═══════════════════════════════════════════════════════"
echo -e "${GREEN}Build completed successfully!${NC}"
echo "═══════════════════════════════════════════════════════"
echo ""
echo "Generated files:"
echo "  Rust library:  target/release/libwebpage_quality_analyzer.a"
echo "  C++ examples:  build/bindings/cpp/examples/"
echo ""
echo "Available examples:"
echo "  • level1_simple       - Simple API usage"
echo "  • level2_builder      - Builder pattern"
echo "  • level3_config       - Config file loading"
echo "  • metrics_showcase    - All metrics demonstration"
echo "  • batch_processing    - Batch URL processing"
echo "  • error_handling      - Error handling patterns"
echo ""
echo "Run an example:"
echo "  ./build/bindings/cpp/examples/level1_simple"
echo ""
echo "Clean build:"
echo "  rm -rf build"
echo "  cargo clean"
echo ""
