#!/bin/bash

# Coverage script for wasot
# Prerequisites: cargo install --locked cargo-llvm-cov cargo-nextest
#
# Usage:
#   ./scripts/coverage.sh           # Run fast tests only (default)
#   ./scripts/coverage.sh --all     # Run all tests including slow/ignored tests
#   ./scripts/coverage.sh --slow    # Run only slow/ignored tests

set -euo pipefail

COVERAGE_DIR="coverage"
RUN_IGNORED="default"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --all)
            RUN_IGNORED="all"
            shift
            ;;
        --slow)
            RUN_IGNORED="only"
            shift
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--all|--slow]"
            exit 1
            ;;
    esac
done

echo "Generating coverage reports..."
echo "Test mode: $RUN_IGNORED (fast only=default, slow only=only, all=all)"

# Check if cargo-llvm-cov is installed
if ! command -v cargo-llvm-cov &> /dev/null; then
    echo "Installing cargo-llvm-cov..."
    cargo install cargo-llvm-cov
fi

# Check if cargo-nextest is installed
if ! command -v cargo-nextest &> /dev/null; then
    echo "Installing cargo-nextest..."
    cargo install --locked cargo-nextest
fi

# Clear and create coverage directory
rm -rf "$COVERAGE_DIR"
mkdir -p "$COVERAGE_DIR"

echo "Running tests with coverage..."
cargo llvm-cov clean
cargo llvm-cov nextest --retries 3 --html --run-ignored "$RUN_IGNORED"

echo "Generating coverage reports..."

# Generate machine-readable LCOV format
cargo llvm-cov report --lcov --output-path "$COVERAGE_DIR/lcov.info"

# Generate machine-readable JSON format
cargo llvm-cov report --json --output-path "$COVERAGE_DIR/coverage.json"

# Generate human-readable HTML report
cargo llvm-cov report --html --output-dir "$COVERAGE_DIR/html"

# Generate human-readable text summary
cargo llvm-cov report > "$COVERAGE_DIR/summary.txt"

echo "Coverage reports generated in $COVERAGE_DIR/"
echo "- Machine-readable: lcov.info, coverage.json"
echo "- Human-readable: html/index.html, summary.txt"
echo ""
echo "Coverage Summary:"
cat "$COVERAGE_DIR/summary.txt"