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

usage() {
  echo "usage: ctgov-request-log <run|run-with-mychem|show|show-interventions|clear> [command ...]" >&2
}

request_log="${BIOMCP_CTGOV_INTERVENTION_ALIAS_REQUEST_LOG:-}"
fixture_root="${BIOMCP_CTGOV_INTERVENTION_ALIAS_ROOT:-}"
mychem_base="${BIOMCP_CTGOV_INTERVENTION_ALIAS_MYCHEM_BASE:-}"

if [[ -z "$request_log" || -z "$fixture_root" ]]; then
  echo "ctgov request log fixture is not configured" >&2
  exit 2
fi

case "$request_log" in
  "$fixture_root"/*) ;;
  *)
    echo "ctgov request log path is outside the fixture root" >&2
    exit 2
    ;;
esac

case "${1:-}" in
  clear)
    : >"$request_log"
    ;;
  show)
    cat "$request_log"
    ;;
  show-interventions)
    uv run --no-sync python - "$request_log" <<'PY'
from pathlib import Path
from urllib.parse import parse_qs, urlparse
import sys

for request in Path(sys.argv[1]).read_text(encoding="utf-8").splitlines():
    for intervention in parse_qs(urlparse(request).query).get("query.intr", []):
        print(intervention)
PY
    ;;
  run)
    shift
    if (($# == 0)); then
      usage
      exit 2
    fi
    : >"$request_log"
    "$@"
    ;;
  run-with-mychem)
    shift
    if (($# == 0)) || [[ -z "$mychem_base" ]]; then
      usage
      exit 2
    fi
    : >"$request_log"
    BIOMCP_MYCHEM_BASE="$mychem_base" "$@"
    ;;
  *)
    usage
    exit 2
    ;;
esac
