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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
# shellcheck disable=SC1091
source "$ROOT_DIR/scripts/acceptance/route_acceptance_lib.sh"

CRM_BASE="${CRM_BASE:-https://sub.tksea.top/portal-admin-api}"
TS="${TS:-$(timestamp_token)}"
MATRIX_DIR="${MATRIX_DIR:-$ROUTE_MATRIX_ROOT/${TS}_route_matrix}"

mkdir -p "$MATRIX_DIR"

run_step() {
  local name="$1"
  shift
  echo "==> $name"
  ARTIFACT_DIR="$MATRIX_DIR/$name" "$@"
}

run_step control_plane bash "$ROOT_DIR/scripts/acceptance/verify_route_control_plane.sh"
run_step health_ui bash "$ROOT_DIR/scripts/acceptance/verify_route_health_ui.sh"
run_step data_plane bash "$ROOT_DIR/scripts/acceptance/verify_route_data_plane.sh"

python3 - "$MATRIX_DIR" >"$MATRIX_DIR/summary.json" <<'PY'
import json
import sys
from pathlib import Path

matrix_dir = Path(sys.argv[1])
control = json.loads((matrix_dir / "control_plane" / "10-summary.json").read_text())
health = json.loads((matrix_dir / "health_ui" / "12-summary.json").read_text())
data = json.loads((matrix_dir / "data_plane" / "07-summary.json").read_text())

summary = {
    "matrix_dir": str(matrix_dir),
    "control_plane_group_id": control["group_id"],
    "health_ui_group_id": health["group_id"],
    "data_plane_group_id": data["group_id"],
    "data_plane_request_id": data["request_id"],
    "data_plane_upstream_status": data["forward_upstream_status"],
    "health_ui_resolve_route_id": health["resolve_route_id"],
}
print(json.dumps(summary, ensure_ascii=False, indent=2))
PY

cat "$MATRIX_DIR/summary.json"
