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

TARGET_URL="${1:-https://codecr.org/}"
PROBE_REGION="${CODECR_PROBE_REGION:-unassigned}"
RUN_STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
OUTPUT_CSV="${2:-codecr-ttfb-${PROBE_REGION}-${RUN_STAMP}.csv}"
SAMPLE_COUNT=5
TTFB_TARGET_SECONDS=1.2

if ! command -v curl >/dev/null 2>&1; then
  echo "ERROR: curl is required." >&2
  exit 2
fi

case "$TARGET_URL" in
  https://*) ;;
  *) echo "ERROR: target URL must use HTTPS." >&2; exit 2 ;;
esac

append_probe_query() {
  local base_url="$1"
  local probe_value="$2"
  if [[ "$base_url" == *\?* ]]; then
    printf '%s&codecr_ttfb_probe=%s' "$base_url" "$probe_value"
  else
    printf '%s?codecr_ttfb_probe=%s' "$base_url" "$probe_value"
  fi
}

PROBE_TMP="$(mktemp -d)"
trap 'rm -rf -- "$PROBE_TMP"' EXIT

printf '%s\n' 'run_id,mode,sample,region,timestamp_utc,http_status,remote_ip,dns_s,connect_s,tls_s,ttfb_s,total_s,url,cf_cache_status,cf_ray' > "$OUTPUT_CSV"

measure_request() {
  local mode="$1"
  local sample="$2"
  local request_url="$3"
  local cache_directive="$4"
  local header_file="$PROBE_TMP/${mode}-${sample}.headers"
  local metrics
  local cache_status
  local cf_ray

  metrics="$(curl --silent --show-error --location --fail-with-body \
    --connect-timeout 10 --max-time 30 \
    --user-agent 'codecr-ttfb-validator/1.0' \
    --header "$cache_directive" \
    --dump-header "$header_file" \
    --output /dev/null \
    --write-out '%{http_code},%{remote_ip},%{time_namelookup},%{time_connect},%{time_appconnect},%{time_starttransfer},%{time_total},%{url_effective}' \
    "$request_url")"

  cache_status="$(awk -F ': *' 'tolower($1) == "cf-cache-status" {gsub(/\r/, "", $2); value=$2} END {print value}' "$header_file")"
  cf_ray="$(awk -F ': *' 'tolower($1) == "cf-ray" {gsub(/\r/, "", $2); value=$2} END {print value}' "$header_file")"
  cache_status="${cache_status:-UNSET}"
  cf_ray="${cf_ray:-UNSET}"

  printf '%s,%s,%s,%s,%s,%s,%s,%s\n' \
    "$RUN_STAMP" "$mode" "$sample" "$PROBE_REGION" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    "$metrics" "$cache_status" "$cf_ray" >> "$OUTPUT_CSV"
}

echo "codecr TTFB validation"
echo "target: $TARGET_URL"
echo "region: $PROBE_REGION"
echo "samples: $SAMPLE_COUNT cold + $SAMPLE_COUNT warm"
echo

for sample in $(seq 1 "$SAMPLE_COUNT"); do
  cold_url="$(append_probe_query "$TARGET_URL" "${RUN_STAMP}-cold-${sample}")"
  echo "cold ${sample}/${SAMPLE_COUNT}"
  measure_request "cold" "$sample" "$cold_url" "Cache-Control: no-cache"
done

warm_url="$(append_probe_query "$TARGET_URL" "${RUN_STAMP}-warm")"
echo "priming warm cache key"
curl --silent --show-error --location --fail-with-body \
  --connect-timeout 10 --max-time 30 \
  --user-agent 'codecr-ttfb-validator/1.0' \
  --output /dev/null "$warm_url"

for sample in $(seq 1 "$SAMPLE_COUNT"); do
  echo "warm ${sample}/${SAMPLE_COUNT}"
  measure_request "warm" "$sample" "$warm_url" "Accept: text/html"
done

percentile_95() {
  local mode="$1"
  awk -F, -v wanted="$mode" 'NR > 1 && $2 == wanted {print $11}' "$OUTPUT_CSV" \
    | sort -n \
    | awk '{sample[NR]=$1} END {if (NR == 0) exit 1; rank=int((NR * 95 + 99) / 100); if (rank < 1) rank=1; if (rank > NR) rank=NR; printf "%.6f", sample[rank]}'
}

cold_p95="$(percentile_95 cold)"
warm_p95="$(percentile_95 warm)"

printf '\ncold p95 TTFB: %ss\n' "$cold_p95"
printf 'warm p95 TTFB: %ss\n' "$warm_p95"

if awk -v cold="$cold_p95" -v warm="$warm_p95" -v target="$TTFB_TARGET_SECONDS" 'BEGIN {exit ! (cold < target && warm < target)}'; then
  echo "PASS: both p95 values are below ${TTFB_TARGET_SECONDS}s."
  result=0
else
  echo "FAIL: one or more p95 values meet or exceed ${TTFB_TARGET_SECONDS}s."
  result=1
fi

echo "evidence: $OUTPUT_CSV"
echo "NOTE: repeat this probe from every contracted geography. A single runner cannot establish a global SLA."
echo "NOTE: cold samples require the codecr_ttfb_probe query parameter to participate in the cache key; otherwise pair the run with an approved purge."
exit "$result"
