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

usage() {
  cat >&2 <<'EOF'
Usage:
  semantic_index/search.sh "query text" [project_identifier] [limit]

Examples:
  semantic_index/search.sh "goods return" customer-service 3
  semantic_index/search.sh "candidate follow up" hiring 5 | jq '.results[] | {id, score, citation}'

Environment:
  SEMANTIC_INDEX_URL      default: http://127.0.0.1:8787
  SEMANTIC_INDEX_API_KEY  optional; falls back to semantic_index/.env or .env
EOF
}

if [[ $# -lt 1 ]]; then
  usage
  exit 2
fi

query=$1
project=${2:-}
limit=${3:-10}
base_url=${SEMANTIC_INDEX_URL:-http://127.0.0.1:8787}
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
install_root=$(cd "$script_dir/.." && pwd)

read_env_value() {
  local key=$1
  local file
  for file in /etc/semantic-index.env "$install_root/semantic_index/.env" "$install_root/.env" semantic_index/.env .env; do
    if [[ -f "$file" ]]; then
      awk -F= -v key="$key" '
        $1 == key {
          value = substr($0, index($0, "=") + 1)
          gsub(/^[ \t"'\''"]+|[ \t"'\''"]+$/, "", value)
          print value
          exit
        }
      ' "$file"
      return
    fi
  done
}

json_escape() {
  sed \
    -e 's/\\/\\\\/g' \
    -e 's/"/\\"/g' \
    -e ':a;N;$!ba;s/\n/\\n/g'
}

escaped_query=$(printf '%s' "$query" | json_escape)
payload="{\"query\":\"$escaped_query\",\"limit\":$limit"
if [[ -n "$project" ]]; then
  escaped_project=$(printf '%s' "$project" | json_escape)
  payload="$payload,\"project_identifier\":\"$escaped_project\""
fi
payload="$payload}"

api_key=${SEMANTIC_INDEX_API_KEY:-$(read_env_value SEMANTIC_INDEX_API_KEY)}

args=(-sS -H "Content-Type: application/json" -d "$payload")
if [[ -n "${api_key:-}" ]]; then
  args+=(-H "Authorization: Bearer $api_key")
fi

curl "${args[@]}" "$base_url/search"
