#!/bin/bash
# CI/CD script for Aprender
# Generated by bashrs - DO NOT EDIT MANUALLY
# Source: scripts/ci.rs

set -euo pipefail

echo "🚀 Aprender CI/CD Pipeline"
echo "=========================="
echo ""

# Configuration
COVERAGE_THRESHOLD=85

# Step 1: Format check
echo "📝 [1/7] Format check..."
if ! cargo fmt --check; then
    echo "❌ Format check failed"
    exit 1
fi
echo "✅ Format check passed"

# Step 2: Clippy
echo "🔍 [2/7] Clippy analysis..."
if ! cargo clippy --all-targets -- -D warnings; then
    echo "❌ Clippy check failed"
    exit 1
fi
echo "✅ Clippy check passed"

# Step 3: Unit tests
echo "🧪 [3/7] Unit tests..."
if ! cargo test --lib; then
    echo "❌ Unit tests failed"
    exit 1
fi
echo "✅ Unit tests passed"

# Step 4: Property tests
echo "🎲 [4/7] Property tests (256 cases)..."
if ! PROPTEST_CASES=256 cargo test --test property_tests; then
    echo "❌ Property tests failed"
    exit 1
fi
echo "✅ Property tests passed"

# Step 5: Doc tests
echo "📚 [5/7] Documentation tests..."
if ! cargo test --doc; then
    echo "❌ Doc tests failed"
    exit 1
fi
echo "✅ Doc tests passed"

# Step 6: Coverage (optional, requires cargo-llvm-cov)
echo "📊 [6/7] Coverage analysis..."
if command -v cargo-llvm-cov &> /dev/null; then
    # Temporarily disable mold linker (breaks LLVM coverage)
    if [ -f ~/.cargo/config.toml ]; then
        mv ~/.cargo/config.toml ~/.cargo/config.toml.ci-backup
    fi

    cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info
    COVERAGE=$(cargo llvm-cov report --summary-only 2>&1 | grep "TOTAL" | awk '{print $10}' | tr -d '%')

    # Restore mold linker
    if [ -f ~/.cargo/config.toml.ci-backup ]; then
        mv ~/.cargo/config.toml.ci-backup ~/.cargo/config.toml
    fi

    echo "Coverage: ${COVERAGE}%"
    if (( $(echo "$COVERAGE < $COVERAGE_THRESHOLD" | bc -l) )); then
        echo "⚠️  Coverage ${COVERAGE}% below threshold ${COVERAGE_THRESHOLD}%"
    else
        echo "✅ Coverage check passed"
    fi
else
    echo "⚠️  cargo-llvm-cov not installed, skipping coverage"
fi

# Step 7: TDG Score (optional, requires pmat)
echo "📈 [7/7] TDG Score analysis..."
if command -v pmat &> /dev/null; then
    TDG_OUTPUT=$(pmat tdg 2>&1)
    echo "$TDG_OUTPUT"
    echo "✅ TDG analysis complete"
else
    echo "⚠️  pmat not installed, skipping TDG analysis"
fi

echo ""
echo "🎉 CI/CD Pipeline Complete!"
echo ""

exit 0
