#!/usr/bin/env bash
#
# Reproduction harness for the github_cli search bug.
#
# Fires several query variants at the *legacy* GitHub code search API
# (GET /search/code) — the same endpoint github_client.py uses — and prints
# the total_count plus the first few repo/path hits for each.
#
# This lets us compare:
#   - quoted phrase vs. unquoted OR query (Bug 3)
#   - dotted/@-containing terms vs. plain tokens (Bug 2)
#   - repo: with and without owner (Bug 1)
#
# Requires GITHUB_TOKEN in the environment.

set -euo pipefail

: "${GITHUB_TOKEN:?GITHUB_TOKEN must be set}"

API='https://api.github.com/search/code'

# Run one query, print total_count + up to 5 "repo  path" lines.
run() {
  local label="$1" q="$2"
  echo "=============================================================="
  echo "LABEL: ${label}"
  echo "QUERY: ${q}"
  local resp
  resp="$(curl -sS \
    -H "Authorization: Bearer ${GITHUB_TOKEN}" \
    -H "Accept: application/vnd.github+json" \
    -H "X-GitHub-Api-Version: 2022-11-28" \
    --get "${API}" \
    --data-urlencode "q=${q}" \
    --data-urlencode "per_page=10")"
  # Surface API errors (e.g. 422 validation) instead of silently showing 0.
  if echo "${resp}" | jq -e 'has("message")' >/dev/null 2>&1 && \
     [ "$(echo "${resp}" | jq -r '.message // empty')" != "" ]; then
    echo "API ERROR: $(echo "${resp}" | jq -r '.message')"
    echo "${resp}" | jq -r '.errors? // empty'
  else
    echo "total_count: $(echo "${resp}" | jq -r '.total_count')"
    echo "${resp}" | jq -r '.items[]? | "  " + .repository.full_name + "  " + .path' | head -5
  fi
  echo
  # The /search/code API is rate limited to ~10 req/min; space requests out.
  sleep 7
}

ORG='theorchard'

# --- The three identifier forms requested ---------------------------------
# (a) full email, quoted phrase
run "email / quoted"          "\"boris.babiy.sme@sonymusic-pde.com\" org:${ORG} in:file language:Terraform"
# (b) email username (with dots), quoted phrase
run "boris.babiy.sme / quoted" "\"boris.babiy.sme\" org:${ORG} in:file language:Terraform"
# (c) the 'boris.babiy' substring you matched manually with `gh search code`
run "boris.babiy / quoted"    "\"boris.babiy\" org:${ORG} in:file language:Terraform"
# (d) the initial+lastname form the handler generates
run "bbabiy / quoted"         "\"bbabiy\" org:${ORG} in:file language:Terraform"

# --- What the handler ACTUALLY sends (unquoted OR, Bug 3) ------------------
run "handler unquoted OR (no repo_filter)" \
  "boris.babiy.sme@sonymusic-pde.com OR boris.babiy.sme OR bbabiy org:${ORG} in:file language:Terraform -repo:theorchard/collab"

# --- Bug 1: repo_filter without owner vs. with owner ----------------------
run "repo:terraform-infra (no owner — Bug 1)" \
  "\"boris.babiy.sme@sonymusic-pde.com\" org:${ORG} in:file language:Terraform repo:terraform-infra"
run "repo:theorchard/terraform-infra (owner)" \
  "\"boris.babiy.sme@sonymusic-pde.com\" org:${ORG} in:file language:Terraform repo:theorchard/terraform-infra"
