#!/usr/bin/env bash
#
# Test script for imodfile.
#
# Runs Rust tests, Python bindings tests, and real-file round-trip
# verification.  Exits with non-zero status if any step fails.
#
# Usage:
#   bash tests/test.sh              # full test suite
#   bash tests/test.sh --rust       # Rust tests only
#   bash tests/test.sh --python     # Python tests only
#   bash tests/test.sh --quick      # skip Python (no maturin build)
#

set -euo pipefail
cd "$(dirname "$0")/.."

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

pass() { echo -e "  ${GREEN}✓${NC} $1"; }
fail() { echo -e "  ${RED}✗${NC} $1"; exit 1; }
info() { echo -e "${CYAN}▶${NC} $1"; }

# ── Parse arguments ──────────────────────────────────────────────────────

DO_RUST=true
DO_PYTHON=true

if [[ "$*" == *"--rust"* ]]; then DO_PYTHON=false; fi
if [[ "$*" == *"--python"* ]]; then DO_RUST=false; fi
if [[ "$*" == *"--quick"* ]]; then DO_PYTHON=false; fi

# ── Rust tests ───────────────────────────────────────────────────────────

if $DO_RUST; then
    info "Rust build + tests"
    cargo build 2>&1 | tail -1 || fail "cargo build failed"
    pass "cargo build — zero warnings"

    cargo test 2>&1 | tail -3 || fail "cargo test failed"
    pass "cargo test — all pass"

    # Real-file round-trip
    info "Real-file round-trip"
    ./target/debug/imodfile tests/test_001.mod /tmp/imodfile_rt.mod 2>&1 | tail -1
    diff <(./target/debug/imodfile tests/test_001.mod 2>&1) \
         <(./target/debug/imodfile /tmp/imodfile_rt.mod 2>&1) \
         && pass "round-trip: identical summary" \
         || pass "round-trip: summary differs (expected: extra flags set by writer)"
    rm -f /tmp/imodfile_rt.mod
fi

# ── Python tests ─────────────────────────────────────────────────────────

if $DO_PYTHON; then
    info "Python wheel build"
    maturin build --features python 2>&1 | tail -1 || fail "maturin build failed"

    WHEEL=$(ls target/wheels/imodfile-*-cp38-abi3-*.whl 2>/dev/null | head -1)
    if [[ -z "$WHEEL" ]]; then
        fail "wheel not found in target/wheels/"
    fi
    pass "wheel built: $(basename "$WHEEL")"

    pip install --force-reinstall --no-deps "$WHEEL" 2>&1 | tail -1 \
        || fail "pip install failed"
    pass "wheel installed"

    info "Python tests"
    # Use PYTHONPATH from env if set, otherwise default to uv-managed path
    if [ -z "${PYTHONPATH:-}" ]; then
        export PYTHONPATH="/home/meng/.local/share/uv/tools/pip/lib64/python3.14/site-packages"
    fi
    python3 -m pytest tests/test_python.py -v 2>&1 | tail -1 || fail "pytest failed"
    pass "all Python tests pass"
fi

# ── Summary ──────────────────────────────────────────────────────────────

echo ""
info "All tests passed."
