#!/bin/bash

set -e

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

echo "Root directory is: $ROOT_DIR"
echo "▶ Running linting..."
yamllint -s docker-compose.yaml
ruff check .
ruff format . --check --diff
mypy integration src config.py

mkdir -p "$ROOT_DIR/report"

if [ -z "$FUNCTION_NAME" ]; then
  echo "▶ Running integration tests for all lambdas in parallel (xdist)..."
  pytest -n auto --dist=loadfile -o addopts= \
    "$ROOT_DIR"/integration/*/test*.py \
    --html=report/report_all.html --self-contained-html \
    --reruns 1 --reruns-delay 1
  echo "✅ Lambda integration tests done. View test report here: report/report_all.html"
else
  echo "▶ Running integration tests for lambda: $FUNCTION_NAME"
  LAMBDA_DIR="$ROOT_DIR/integration/$FUNCTION_NAME"
  REPORT_PREFIX=$([ -n "$LAMBDA_ENDPOINT_URL" ] && echo "report_rie" || echo "report")
  REPORT_FILE="report/${REPORT_PREFIX}_${FUNCTION_NAME}.html"
  if [ -d "$LAMBDA_DIR" ]; then
    echo "→ Testing $FUNCTION_NAME"
    pytest -o addopts= "$LAMBDA_DIR"/test*.py \
      --html="$REPORT_FILE" --self-contained-html \
      --reruns 1 --reruns-delay 1
    echo "✅ Lambda integration tests done. View test report here: $REPORT_FILE"
  else
    echo "⚠️ Skipping integration tests for $FUNCTION_NAME: No tests in '$LAMBDA_DIR'."
    exit 0
  fi
fi
