#!/usr/bin/env bash

function error_handler() {
  >&2 echo "Exited with BAD EXIT CODE '${2}' in ${0} script at line: ${1}."
  exit "$2"
}
trap 'error_handler ${LINENO} $?' ERR
set -o errtrace -o errexit -o nounset -o pipefail

script_dir="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
supported_session_types=$(grep -E '^(el)?if.*\<session_type\>.*==' "$0" | sed -E 's/.*== "([^"]+)".*/\1/' | tr '\n' ' ')

session_type="${1:-}"
shift
if [[ -z "${session_type}" ]] || ! grep -qE "\<${session_type}\>" <<<"$supported_session_types"; then
  if [[ -n "$session_type" ]]; then
    >&2 echo "ERROR: Given session typeis not supported - ${session_type}"
  fi

  >&2 echo "usage: $(basename "$0") [session_type]"
  >&2 echo -e "\tsupported session types: ${supported_session_types}"
  exit 1
fi

if [[ -z "${SPIFFWORKFLOW_BACKEND_RUNNING_IN_CI:-}" ]]; then
  export FLASK_SESSION_SECRET_KEY=super_secret_key
  export FORCE_COLOR="1"
  export PRE_COMMIT_COLOR="always"
  export SPIFFWORKFLOW_BACKEND_DATABASE_PASSWORD=
  export SPIFFWORKFLOW_BACKEND_DATABASE_TYPE=mysql
  export SPIFFWORKFLOW_BACKEND_RUNNING_IN_CI='true'
fi

function setup_db_for_ci() {
  # Set environment variables
  export FLASK_INSTANCE_PATH="${script_dir}/../src/instance"
  export FLASK_SESSION_SECRET_KEY="e7711a3ba96c46c68e084a86952de16f"
  export FLASK_APP="src/spiffworkflow_backend"
  export SPIFFWORKFLOW_BACKEND_ENV="unit_testing"

  # Check if SPIFFWORKFLOW_BACKEND_DATABASE_TYPE is set to "sqlite"
  if [[ "$SPIFFWORKFLOW_BACKEND_DATABASE_TYPE" == "sqlite" ]]; then
    # Remove existing migrations folder if it exists
    if [[ -d "migrations" ]]; then
      rm -rf "migrations"
    fi

      # Run the 'init' and 'migrate' tasks using flask
      poetry run flask db init
      poetry run flask db migrate
    fi

  # Run the 'upgrade' task using flask
  poetry run flask db upgrade
}

poetry install

if [[ "${session_type}" == "tests" ]]; then
  setup_db_for_ci
  poetry run coverage run --parallel -m pytest "$@"

elif [[ "${session_type}" == "typeguard" ]]; then
  setup_db_for_ci
  RUN_TYPEGUARD=true poetry run pytest "$@"

elif [[ "${session_type}" == "mypy" ]]; then
  poetry run mypy src tests

elif [[ "${session_type}" == "safety" ]]; then
  poetry run safety check --full-report

elif [[ "${session_type}" == "coverage" ]]; then
  if ls .coverage.* 1> /dev/null 2>&1; then
      poetry run coverage combine
  fi
  poetry run coverage report
  poetry run coverage xml
fi