#!/bin/bash
### Run Typesense via Docker ########################################
set -x

export TYPESENSE_API_KEY=xyz
export TYPESENSE_HOST=http://localhost:8108

docker stop typesense-repro 2>/dev/null
docker rm typesense-repro 2>/dev/null
rm -rf "$(pwd)"/typesense-data-dir-repro
mkdir "$(pwd)"/typesense-data-dir-repro

# Start Typesense
docker run -d -p 8108:8108 --name typesense-repro \
            -v"$(pwd)"/typesense-data-dir-repro:/data \
            typesense/typesense:30.0.rc27 \
            --data-dir /data \
            --api-key=$TYPESENSE_API_KEY \
            --enable-cors

# Wait till typesense is ready.
until curl -s -o /dev/null -w "%{http_code}" "$TYPESENSE_HOST/health" -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" | grep -q "200"; do
  echo "Waiting for Typesense..."
  sleep 2
done

echo "Typesense is ready!"

curl -s "$TYPESENSE_HOST/debug" \
       -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" | jq

# Create collection with weighted fields and infix enabled
curl -s "$TYPESENSE_HOST/collections" \
       -X POST \
       -H "Content-Type: application/json" \
       -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
       -d '{
             "name": "events",
             "fields": [
               {"name": "event_ticker", "type": "string" },
               {"name": "computed_title", "type": "string", "infix": true },
               {"name": "event_title", "type": "string", "infix": true },
               {"name": "engagement_score", "type": "float" }
             ],
             "default_sorting_field": "engagement_score"
           }' | jq

# Add documents similar to the real scenario
curl -s "$TYPESENSE_HOST/collections/events/documents/import?action=create" \
        -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
        -H "Content-Type: text/plain" \
        -X POST \
        -d '{"id": "1","event_ticker": "KXNFLGAME-25NOV09DETWAS","computed_title": "NFL Football week 10 Detroit Lions Washington Commanders","event_title": "Football NFL Detroit at Washington","engagement_score": 31.37}
{"id": "2","event_ticker": "KXNFLWINS-DAL-25B","computed_title": "Cowboys pro football wins this season?","event_title": "NFL Dallas pro football wins this season?","engagement_score": 23.51}' | jq

echo ""
echo "=========================================="
echo "ISSUE: best_field_weight reports wrong field when multiple fields match"
echo ""
echo "Setup:"
echo "  - computed_title has weight 16"
echo "  - event_title has weight 15"
echo ""
echo "Query: 'nfl'"
echo ""
echo "Expected for KXNFLGAME-25NOV09DETWAS:"
echo "  - Both fields match 'NFL'"
echo "  - best_field_weight should be 16 (computed_title)"
echo ""
echo "Actual:"
echo "  - best_field_weight is 15 (event_title)"
echo ""
echo "This causes identical text_match scores even though one has a higher weighted field match"
echo "=========================================="
echo ""

# Search with just "nfl" - single word query
echo "=== Full Response ==="
curl -s "$TYPESENSE_HOST/multi_search" \
        -X POST \
        -H "Content-Type: application/json" \
        -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
        -d '{
          "searches": [
            {
              "collection": "events",
              "q": "nfl",
              "query_by": "computed_title,event_title",
              "query_by_weights": "16,15",
              "infix": "always,fallback",
              "prioritize_exact_match": true,
              "text_match_type": "max_weight",
              "sort_by": "_text_match:desc,engagement_score:desc",
              "include_fields": "event_ticker,computed_title,event_title,engagement_score",
              "highlight_full_fields": "computed_title,event_title"
            }
          ]
        }' | jq '.'

echo ""
echo "=== Bug Summary ==="
curl -s "$TYPESENSE_HOST/multi_search" \
        -X POST \
        -H "Content-Type: application/json" \
        -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
        -d '{
          "searches": [
            {
              "collection": "events",
              "q": "nfl",
              "query_by": "computed_title,event_title",
              "query_by_weights": "16,15",
              "infix": "always,fallback",
              "prioritize_exact_match": true,
              "text_match_type": "max_weight",
              "sort_by": "_text_match:desc,engagement_score:desc",
              "include_fields": "event_ticker,computed_title,event_title,engagement_score",
              "highlight_full_fields": "computed_title,event_title"
            }
          ]
        }' | jq -r '.results[0].hits[]? |
"Ticker: \(.document.event_ticker)
  fields_matched: \(.text_match_info.fields_matched)
  best_field_weight: \(.text_match_info.best_field_weight)
  Fields that matched: \(.highlights | map(.field) | join(", "))
\(if (.highlights | map(.field) | contains(["computed_title"])) and .text_match_info.best_field_weight != 16 then
  "\n  ❌ BUG: best_field_weight is \(.text_match_info.best_field_weight) but computed_title (weight=16) also matched!"
else
  ""
end)
"'

echo ""
echo "=========================================="
echo "The bug: When both computed_title (weight 16) and event_title (weight 15) match,"
echo "best_field_weight should be 16, but it's reporting 15 instead."
echo ""
echo "This causes documents with higher-weighted field matches to get the same"
echo "text_match score as documents with lower-weighted field matches."
echo "=========================================="

docker stop typesense-repro
docker rm typesense-repro
