#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
APP_DIR="${ROOT_DIR}/apps/platform"
LANE="${1:-fast-feedback}"
CAPTURE_BASELINE=false
WORKFLOW_ID=""
TRIGGER_CLASS=""

copy_heavy_baseline_artifacts() {
    local artifact_root="${APP_DIR}/storage/logs/test-lanes"
    local suffix

    for suffix in junit.xml summary.md budget.json report.json profile.txt; do
        local latest_path="${artifact_root}/heavy-governance-latest.${suffix}"
        local baseline_path="${artifact_root}/heavy-governance-baseline.${suffix}"

        if [[ -f "${latest_path}" ]]; then
            cp "${latest_path}" "${baseline_path}"
        fi
    done
}

case "${LANE}" in
    fast-feedback|fast|default)
        COMPOSER_SCRIPT="test"
        ;;
    confidence)
        COMPOSER_SCRIPT="test:confidence"
        ;;
    browser)
        COMPOSER_SCRIPT="test:browser"
        ;;
    heavy-governance|heavy)
        COMPOSER_SCRIPT="test:heavy"
        ;;
    profiling|profile)
        COMPOSER_SCRIPT="test:profile"
        ;;
    junit)
        COMPOSER_SCRIPT="test:junit"
        ;;
    *)
        echo "Unknown test lane: ${LANE}" >&2
        exit 1
        ;;
esac

shift || true

remaining_args=()

for arg in "$@"; do
    if [[ "${arg}" == "--capture-baseline" ]]; then
        CAPTURE_BASELINE=true
        continue
    fi

    if [[ "${arg}" == --workflow-id=* ]]; then
        WORKFLOW_ID="${arg#--workflow-id=}"
        continue
    fi

    if [[ "${arg}" == --trigger-class=* ]]; then
        TRIGGER_CLASS="${arg#--trigger-class=}"
        continue
    fi

    remaining_args+=("${arg}")
done

if [[ "${CAPTURE_BASELINE}" == true && "${LANE}" != "heavy-governance" && "${LANE}" != "heavy" ]]; then
    echo "--capture-baseline is only supported for heavy-governance" >&2
    exit 1
fi

if [[ -n "${WORKFLOW_ID}" ]]; then
    export TENANTATLAS_CI_WORKFLOW_ID="${WORKFLOW_ID}"
fi

if [[ -n "${TRIGGER_CLASS}" ]]; then
    export TENANTATLAS_CI_TRIGGER_CLASS="${TRIGGER_CLASS}"
fi

cd "${APP_DIR}"

if [[ ${#remaining_args[@]} -gt 0 ]]; then
    ./vendor/bin/sail composer run --timeout=0 "${COMPOSER_SCRIPT}" -- "${remaining_args[@]}"
else
    ./vendor/bin/sail composer run --timeout=0 "${COMPOSER_SCRIPT}"
fi

if [[ "${CAPTURE_BASELINE}" == true ]]; then
    copy_heavy_baseline_artifacts
fi