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

REPO_DIR="${REPO_DIR:-/home/openclaw/.openclaw/workspace-defaults/repos/dataflow-service}"
TOKEN_HELPER="${TOKEN_HELPER:-/home/openclaw/.openclaw/workspace-defaults/skills/tidbcloud-github-access/scripts/get-gh-token.sh}"
BRANCH="${BRANCH:-master}"
DOMAIN="${DOMAIN:-cdc}"
TEST_ENV="${TEST_ENV:-dev}"
CASE_GROUP="${CASE_GROUP:-smoke}"
CASES="${CASES:-}"
ORG_ID="${ORG_ID:-}"
PROJECT_ID="${PROJECT_ID:-}"
CLUSTER_IDS="${CLUSTER_IDS:-}"
AUTH_TOKEN="${AUTH_TOKEN:-}"
AWS_REGIONS="${AWS_REGIONS:-us-west-2,us-west-1}"
GCP_REGIONS="${GCP_REGIONS:-us-west1,us-west2}"
AZURE_REGIONS="${AZURE_REGIONS:-eastus2,eastus}"

if [[ -z "$AUTH_TOKEN" ]]; then
  echo "AUTH_TOKEN is required. Provide the TiDB Cloud bearer token without the 'Bearer ' prefix." >&2
  exit 2
fi

if [[ ! -d "$REPO_DIR/.git" ]]; then
  echo "Repo not found: $REPO_DIR" >&2
  exit 2
fi

if [[ ! -x "$TOKEN_HELPER" ]]; then
  echo "GitHub App token helper not found/executable: $TOKEN_HELPER" >&2
  exit 2
fi

export GH_TOKEN="$($TOKEN_HELPER)"
cd "$REPO_DIR"

exec gh workflow run e2e-test.yaml \
  --repo tidbcloud/dataflow-service \
  --ref "$BRANCH" \
  -f executor=ci \
  -f domain="$DOMAIN" \
  -f env="$TEST_ENV" \
  -f case_group="$CASE_GROUP" \
  -f cases="$CASES" \
  -f org_id="$ORG_ID" \
  -f project_id="$PROJECT_ID" \
  -f cluster_ids="$CLUSTER_IDS" \
  -f auth_token="$AUTH_TOKEN" \
  -f aws_regions="$AWS_REGIONS" \
  -f gcp_regions="$GCP_REGIONS" \
  -f azure_regions="$AZURE_REGIONS"
