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

source ./scripts/Unix/starter.sh

report=""
omit_pattern='storefront/*,monitoring/*,Dockerfiles/*,*/__init__.py,*/tests/*,*/migrations/*,manage.py,evibes/*'

while [ "$#" -gt 0 ]; do
    case "$1" in
        --report|-r)
            if [ "${2-}" = "" ]; then
                log_error "Error: --report/-r requires an argument: xml or html"
                exit 1
            fi
            report="$2"
            shift 2
            ;;
        --report=*)
            report="${1#*=}"
            shift
            ;;
        -r=*)
            report="${1#*=}"
            shift
            ;;
        *)
            log_error "Unknown argument: $1"
            echo "Usage: $0 [--report|-r xml|html]" >&2
            exit 1
            ;;
    esac
done

case "${report:-}" in
    "")
        log_step "Running tests with coverage..."

        log_info "  → Erasing previous coverage data..."
        if ! docker compose exec app uv run coverage erase; then
            log_error "Failed to erase coverage data"
            exit 1
        fi

        log_info "  → Running tests..."
        if ! docker compose exec app uv run coverage run --source='.' --omit="$omit_pattern" manage.py test; then
            log_error "Tests failed"
            exit 1
        fi

        log_info "  → Generating coverage report..."
        docker compose exec app uv run coverage report -m
        ;;
    xml)
        log_step "Generating XML coverage report..."
        if docker compose exec app uv run coverage xml --omit="$omit_pattern"; then
            log_success "XML coverage report generated"
        else
            log_error "Failed to generate XML coverage report"
            exit 1
        fi
        ;;
    html)
        log_step "Generating HTML coverage report..."
        if docker compose exec app uv run coverage html --omit="$omit_pattern"; then
            log_success "HTML coverage report generated"
        else
            log_error "Failed to generate HTML coverage report"
            exit 1
        fi
        ;;
    *)
        log_error "Invalid report type: $report (expected xml or html)"
        exit 1
        ;;
esac
