#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR"

FULL_CLEAN_FLAG=0
OPEN_HTML_FLAG=${OPEN_HTML:-0}
for arg in "$@"; do
  case "$arg" in
    --full-clean|-c)
      FULL_CLEAN_FLAG=1
      ;;
    --open)
      OPEN_HTML_FLAG=1
      ;;
    --help|-h)
      echo "Usage: $0 [--full-clean|-c] [--open]"
      echo "  --full-clean, -c  Remove prior coverage output before running"
      echo "  --open            Open the HTML report after generation"
      exit 0
      ;;
  esac
done

if (( FULL_CLEAN_FLAG )); then
  rm -rf .coverage htmlcov coverage.xml
fi

echo "==> Running unit tests with coverage"
python3 -m coverage run -m pytest -q tests/unit

echo "==> Coverage summary"
python3 -m coverage report -m

echo "==> Writing HTML and XML coverage"
python3 -m coverage html
python3 -m coverage xml

echo "HTML report: htmlcov/index.html"
echo "XML report: coverage.xml"

if (( OPEN_HTML_FLAG )); then
  open htmlcov/index.html >/dev/null 2>&1 || true
fi
