#!/usr/bin/env bash
# One-time Guard staging check (Linux).
# 1) Sends pairs in batches of 6 starts per second
# 2) Waits/polls for Guard result POSTs (results can arrive late)
# 3) Joins start HTTP status + reptest_outgoing_response into a CSV report
#
#   export GUARD_STAGING_URL="https://guard-lb.dev.numbersentry.io:443/"
#   export GUARD_API_KEY="your-key"
#   ./scripts/guard-staging-call-loop.sh
#
# Rebuild CSV later without placing new calls (after more results arrive):
#   ./scripts/guard-staging-call-loop.sh --rebuild-only \
#     scripts/logs/guard-staging-XXXX-starts.tsv \
#     scripts/logs/guard-staging-XXXX-meta.txt
set -euo pipefail

BASE_URL="${GUARD_STAGING_URL:-https://guard-lb.dev.numbersentry.io:443/}"
API_KEY="${GUARD_API_KEY:-}"
CALL_TIMEOUT="${GUARD_CALL_TIMEOUT:-1}"
TYPE="${GUARD_TYPE:-021}"
PROVIDER="${GUARD_PROVIDER:-inteliquent}"
HTTP_TIMEOUT="${GUARD_HTTP_TIMEOUT:-150}"
BATCH_SIZE="${GUARD_BATCH_SIZE:-6}"
BATCH_INTERVAL="${GUARD_BATCH_INTERVAL:-1}"
# Initial wait after starts, then poll until complete or max reached.
WAIT_EXTRA="${GUARD_WAIT_EXTRA:-300}"
POLL_INTERVAL="${GUARD_POLL_INTERVAL:-30}"
POLL_MAX_SECONDS="${GUARD_POLL_MAX_SECONDS:-1200}"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PAIRS_FILE="${GUARD_PAIRS_FILE:-$SCRIPT_DIR/guard-call-pairs.csv}"
LOG_DIR="$SCRIPT_DIR/logs"
mkdir -p "$LOG_DIR"

REBUILD_ONLY=0
REBUILD_FROM_REPORT=0
if [[ "${1:-}" == "--rebuild-only" ]]; then
  REBUILD_ONLY=1
  STARTS_IN="${2:-}"
  META_IN="${3:-}"
  if [[ -z "$STARTS_IN" || -z "$META_IN" || ! -f "$STARTS_IN" || ! -f "$META_IN" ]]; then
    echo "Usage: $0 --rebuild-only <starts.tsv> <meta.txt>" >&2
    exit 1
  fi
  # shellcheck disable=SC1090
  source "$META_IN"
  STAMP="rebuild-$(date +%Y%m%d-%H%M%S)"
elif [[ "${1:-}" == "--rebuild-from-report" ]]; then
  # Refresh an old report CSV after waiting longer (no new calls).
  #   ./scripts/guard-staging-call-loop.sh --rebuild-from-report report.csv '2026-11-17 09:00:00'
  REBUILD_FROM_REPORT=1
  REPORT_IN="${2:-}"
  RUN_STARTED_AT="${3:-}"
  if [[ -z "$REPORT_IN" || -z "$RUN_STARTED_AT" || ! -f "$REPORT_IN" ]]; then
    echo "Usage: $0 --rebuild-from-report <old-report.csv> 'YYYY-MM-DD HH:MM:SS'" >&2
    exit 1
  fi
  STAMP="rebuild-$(date +%Y%m%d-%H%M%S)"
else
  STAMP="$(date +%Y%m%d-%H%M%S)"
fi

LOG_FILE="$LOG_DIR/guard-staging-$STAMP.log"
REPORT_CSV="$LOG_DIR/guard-staging-$STAMP-report.csv"
STARTS_SAVE="$LOG_DIR/guard-staging-$STAMP-starts.tsv"
META_SAVE="$LOG_DIR/guard-staging-$STAMP-meta.txt"
RESULT_DIR="$(mktemp -d /tmp/guard-staging-XXXXXX)"
trap 'rm -rf "$RESULT_DIR"' EXIT

log() {
  local line
  line="$(date '+%Y-%m-%d %H:%M:%S')  $*"
  printf '%s\n' "$line" | tee -a "$LOG_FILE"
}

load_db_env() {
  local env_file="${GUARD_ENV_FILE:-$REPO_ROOT/.env}"
  if [[ -f "$env_file" ]]; then
    while IFS= read -r line || [[ -n "$line" ]]; do
      line="${line%$'\r'}"
      case "$line" in
        DB_HOST=*|DB_PORT=*|DB_DATABASE=*|DB_USERNAME=*|DB_PASSWORD=*)
          key="${line%%=*}"
          val="${line#*=}"
          val="${val%\"}"
          val="${val#\"}"
          export "$key=$val"
          ;;
      esac
    done <"$env_file"
  fi
  DB_HOST="${DB_HOST:-127.0.0.1}"
  DB_PORT="${DB_PORT:-3306}"
  DB_DATABASE="${DB_DATABASE:-}"
  DB_USERNAME="${DB_USERNAME:-}"
  DB_PASSWORD="${DB_PASSWORD:-}"
}

fetch_and_build_report() {
  local starts_tsv="$1"
  local run_started_at="$2"
  local out_csv="$3"
  local reptest_tsv="$RESULT_DIR/reptest.tsv"

  MYSQL_PWD="$DB_PASSWORD" mysql \
    -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USERNAME" "$DB_DATABASE" \
    --batch --raw --skip-column-names \
    -e "
SELECT
  calling_number,
  called_number,
  status,
  IFNULL(platform_code, ''),
  IFNULL(request_id, ''),
  IFNULL(detect_call_start_time, ''),
  IFNULL(detect_call_release_time, ''),
  IFNULL(detection_type, ''),
  id
FROM reptest_outgoing_response
WHERE detection_type = '${TYPE}'
  AND detect_call_start_time >= '${run_started_at}'
ORDER BY detect_call_start_time ASC, id ASC;
" >"$reptest_tsv"

  python3 - "$starts_tsv" "$reptest_tsv" "$out_csv" <<'PY'
import csv
import sys
from collections import defaultdict, deque

starts_path, reptest_path, out_path = sys.argv[1:4]

starts = []
with open(starts_path, "r", encoding="utf-8", errors="replace") as f:
    for line in f:
        line = line.rstrip("\n")
        if not line:
            continue
        parts = line.split("\t")
        while len(parts) < 8:
            parts.append("")
        n, request_id, frm, to, http, elapsed, body, err = parts[:8]
        starts.append({
            "n": n,
            "request_id_sent": request_id,
            "from": frm,
            "to": to,
            "guard_http_status": http,
            "guard_elapsed_ms": elapsed,
            "guard_body": body,
            "guard_curl_error": err,
        })

by_pair = defaultdict(deque)
with open(reptest_path, "r", encoding="utf-8", errors="replace") as f:
    for line in f:
        line = line.rstrip("\n")
        if not line:
            continue
        parts = line.split("\t")
        while len(parts) < 9:
            parts.append("")
        calling, called, status, platform, req_id, start_t, release_t, det_type, row_id = parts[:9]
        by_pair[(calling, called)].append({
            "detection_status": status,
            "platform_code": platform,
            "db_request_id": req_id,
            "detect_call_start_time": start_t,
            "detect_call_release_time": release_t,
            "detection_type": det_type,
            "reptest_id": row_id,
        })

fields = [
    "n", "request_id_sent", "from", "to",
    "guard_http_status", "guard_elapsed_ms",
    "detection_status", "platform_code", "db_request_id",
    "detect_call_start_time", "detect_call_release_time",
    "detection_type", "reptest_id",
    "guard_body", "guard_curl_error",
]

found = 0
missing = 0
with open(out_path, "w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=fields)
    writer.writeheader()
    for row in sorted(starts, key=lambda r: int(r["n"] or 0)):
        key = (row["from"], row["to"])
        if by_pair[key]:
            row.update(by_pair[key].popleft())
            found += 1
        else:
            row.update({
                "detection_status": "NOT_FOUND",
                "platform_code": "",
                "db_request_id": "",
                "detect_call_start_time": "",
                "detect_call_release_time": "",
                "detection_type": "",
                "reptest_id": "",
            })
            missing += 1
        writer.writerow(row)

print(f"{found}|{missing}|{len(starts)}")
PY
}

if ! command -v mysql >/dev/null 2>&1; then
  echo "mysql client is required." >&2
  exit 1
fi
if ! command -v python3 >/dev/null 2>&1; then
  echo "python3 is required." >&2
  exit 1
fi

load_db_env
if [[ -z "$DB_DATABASE" || -z "$DB_USERNAME" ]]; then
  echo "DB_DATABASE / DB_USERNAME missing. Set them or provide $REPO_ROOT/.env" >&2
  exit 1
fi

if [[ "$REBUILD_ONLY" -eq 1 ]]; then
  log "rebuild-only starts=$STARTS_IN run_started_at_utc=$RUN_STARTED_AT type=$TYPE"
  STARTS_TSV="$STARTS_IN"
  stats="$(fetch_and_build_report "$STARTS_TSV" "$RUN_STARTED_AT" "$REPORT_CSV")"
  found="${stats%%|*}"
  rest="${stats#*|}"
  missing="${rest%%|*}"
  total="${rest##*|}"
  log "report ready: $REPORT_CSV matched=$found missing=$missing total=$total"
  echo "CSV report: $REPORT_CSV"
  exit 0
fi

if [[ "$REBUILD_FROM_REPORT" -eq 1 ]]; then
  STARTS_TSV="$RESULT_DIR/starts-from-report.tsv"
  python3 - "$REPORT_IN" "$STARTS_TSV" <<'PY'
import csv, sys
src, dst = sys.argv[1:3]
with open(src, newline="", encoding="utf-8", errors="replace") as f, open(dst, "w", encoding="utf-8", newline="") as out:
    reader = csv.DictReader(f)
    for row in reader:
        out.write("\t".join([
            row.get("n", ""),
            row.get("request_id_sent", ""),
            row.get("from", ""),
            row.get("to", ""),
            row.get("guard_http_status", ""),
            row.get("guard_elapsed_ms", ""),
            row.get("guard_body", ""),
            row.get("guard_curl_error", ""),
        ]) + "\n")
PY
  log "rebuild-from-report file=$REPORT_IN since=$RUN_STARTED_AT type=$TYPE"
  stats="$(fetch_and_build_report "$STARTS_TSV" "$RUN_STARTED_AT" "$REPORT_CSV")"
  found="${stats%%|*}"
  rest="${stats#*|}"
  missing="${rest%%|*}"
  total="${rest##*|}"
  log "report ready: $REPORT_CSV matched=$found missing=$missing total=$total"
  echo "CSV report: $REPORT_CSV"
  exit 0
fi

if [[ -z "$API_KEY" || "$API_KEY" == "YOUR_API_KEY" ]]; then
  echo "Set GUARD_API_KEY (x-api-key) before running." >&2
  exit 1
fi
if [[ ! -f "$PAIRS_FILE" ]]; then
  echo "Pairs file not found: $PAIRS_FILE" >&2
  exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
  echo "curl is required." >&2
  exit 1
fi

mapfile -t PAIR_LINES < <(awk -F',' 'NR>1 && $1!="" && $2!="" {gsub(/\r/,"",$1); gsub(/\r/,"",$2); print $1","$2}' "$PAIRS_FILE")
COUNT="${#PAIR_LINES[@]}"
if [[ "$COUNT" -lt 1 ]]; then
  echo "No pairs in $PAIRS_FILE" >&2
  exit 1
fi

ID_BASE="$(date +%s)000"
BASE_URL="${BASE_URL%/}"
RUN_STARTED_AT="$(date -u '+%Y-%m-%d %H:%M:%S')"
# Look a bit earlier to avoid clock skew missing early rows
RUN_STARTED_AT_QUERY="$(date -u -d "$RUN_STARTED_AT UTC - 2 minutes" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || date -u '+%Y-%m-%d %H:%M:%S')"
STARTS_TSV="$RESULT_DIR/starts.tsv"
: >"$STARTS_TSV"

log "start count=$COUNT batch=$BATCH_SIZE every=${BATCH_INTERVAL}s type=$TYPE timeout=$CALL_TIMEOUT url=$BASE_URL"
log "run_started_at_utc=$RUN_STARTED_AT"
log "wait_extra=${WAIT_EXTRA}s poll_every=${POLL_INTERVAL}s poll_max=${POLL_MAX_SECONDS}s"

fire_one() {
  local n="$1" from="$2" to="$3" request_id="$4"
  local url body_file out_file http_code elapsed
  local start_ms end_ms body err

  url="${BASE_URL}/?from=${from}&to=${to}&id=${request_id}&timeout=${CALL_TIMEOUT}&type=${TYPE}&provider=${PROVIDER}"
  body_file="$RESULT_DIR/body-${request_id}.txt"
  out_file="$RESULT_DIR/out-${n}.txt"

  start_ms="$(date +%s%3N)"
  http_code="$(
    curl --silent --show-error --get "$url" \
      -H "x-api-key: ${API_KEY}" \
      -H "Connection: close" \
      --max-time "$HTTP_TIMEOUT" \
      --output "$body_file" \
      --write-out "%{http_code}" \
      2>"$RESULT_DIR/err-${request_id}.txt" || true
  )"
  end_ms="$(date +%s%3N)"
  elapsed=$((end_ms - start_ms))
  [[ -z "$http_code" ]] && http_code="0"

  body="$(tr '\n\t' '  ' <"$body_file" 2>/dev/null || true)"
  err="$(tr '\n\t' '  ' <"$RESULT_DIR/err-${request_id}.txt" 2>/dev/null || true)"

  printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
    "$n" "$request_id" "$from" "$to" "$http_code" "$elapsed" "$body" "$err" >"$out_file"
}

batch_index=0
for ((i = 0; i < COUNT; i += BATCH_SIZE)); do
  batch_index=$((batch_index + 1))
  batch_end=$((i + BATCH_SIZE - 1))
  if ((batch_end >= COUNT)); then
    batch_end=$((COUNT - 1))
  fi

  log "batch $batch_index fire pairs $((i + 1))-$((batch_end + 1))"
  batch_start_s="$(date +%s)"

  for ((j = i; j <= batch_end; j++)); do
    IFS=',' read -r from to <<<"${PAIR_LINES[$j]}"
    n=$((j + 1))
    request_id=$((ID_BASE + n))
    log "queue [$n/$COUNT] id=$request_id from=$from to=$to"
    fire_one "$n" "$from" "$to" "$request_id" &
  done

  if ((batch_end < COUNT - 1)); then
    now_s="$(date +%s)"
    elapsed_s=$((now_s - batch_start_s))
    sleep_for=$((BATCH_INTERVAL - elapsed_s))
    if ((sleep_for > 0)); then
      sleep "$sleep_for"
    fi
  fi
done

log "all batches queued; waiting for HTTP replies..."
wait

for ((n = 1; n <= COUNT; n++)); do
  out_file="$RESULT_DIR/out-${n}.txt"
  if [[ ! -f "$out_file" ]]; then
    log "[$n/$COUNT] MISSING result file"
    printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$n" "" "" "" "0" "0" "" "missing" >>"$STARTS_TSV"
    continue
  fi
  cat "$out_file" >>"$STARTS_TSV"
  IFS=$'\t' read -r n request_id from to http elapsed body err <"$out_file"
  log "[$n/$COUNT] id=$request_id from=$from to=$to guard_http=$http elapsed_ms=$elapsed"
done

# Persist so you can rebuild later without new calls
cp "$STARTS_TSV" "$STARTS_SAVE"
cat >"$META_SAVE" <<EOF
RUN_STARTED_AT='$RUN_STARTED_AT_QUERY'
TYPE='$TYPE'
EOF
log "saved starts=$STARTS_SAVE meta=$META_SAVE"

WAIT_SECONDS=$((CALL_TIMEOUT + WAIT_EXTRA))
log "initial wait ${WAIT_SECONDS}s for Guard result POSTs..."
sleep "$WAIT_SECONDS"

elapsed_poll=0
prev_missing=-1
while true; do
  stats="$(fetch_and_build_report "$STARTS_TSV" "$RUN_STARTED_AT_QUERY" "$REPORT_CSV")"
  found="${stats%%|*}"
  rest="${stats#*|}"
  missing="${rest%%|*}"
  total="${rest##*|}"
  log "poll matched=$found missing=$missing total=$total csv=$REPORT_CSV"

  if [[ "$missing" -eq 0 ]]; then
    log "all detection statuses found"
    break
  fi
  if [[ "$elapsed_poll" -ge "$POLL_MAX_SECONDS" ]]; then
    log "poll max ${POLL_MAX_SECONDS}s reached with missing=$missing"
    break
  fi
  if [[ "$missing" -eq "$prev_missing" && "$elapsed_poll" -ge 300 ]]; then
    # after 5 min of polling with no improvement, keep going until max
    :
  fi
  prev_missing="$missing"
  sleep "$POLL_INTERVAL"
  elapsed_poll=$((elapsed_poll + POLL_INTERVAL))
done

log "report ready: $REPORT_CSV"
log "If still NOT_FOUND, wait more and rebuild:"
log "  ./scripts/guard-staging-call-loop.sh --rebuild-only $STARTS_SAVE $META_SAVE"
echo
echo "CSV report: $REPORT_CSV"
echo "Starts saved: $STARTS_SAVE"
