#!/bin/bash
### Repro 2: Same starting tokens, different endings
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 /tmp/typesense-data-dir-repro
mkdir /tmp/typesense-data-dir-repro

docker run -d -p 8108:8108 --name typesense-repro \
    -v/tmp/typesense-data-dir-repro:/data \
    typesense/typesense:30.0.rca31 \
    --data-dir /data --api-key=$TYPESENSE_API_KEY --enable-cors

until curl -s -o /dev/null -w "%{http_code}" "$TYPESENSE_HOST/health" -H "X-TYPESENSE-API-KEY: xyz" | grep -q "200"; do sleep 1; done

curl -s "$TYPESENSE_HOST/collections" -X POST -H "Content-Type: application/json" -H "X-TYPESENSE-API-KEY: xyz" \
    -d '{"name": "events", "fields": [{"name": "title", "type": "string"}]}' | jq

curl -s "$TYPESENSE_HOST/collections/events/documents/import?action=create" \
    -H "X-TYPESENSE-API-KEY: xyz" -H "Content-Type: text/plain" -X POST \
    -d '{"id": "1", "title": "Florida State at Florida mens basketball"}
{"id": "2", "title": "Florida State at Alabama State mens basketball"}' | jq

echo ""
echo "=== Query: 'Florida State at Florida' ==="
curl -s "$TYPESENSE_HOST/collections/events/documents/search" -G \
    --data-urlencode "q=Florida State at Florida" \
    --data-urlencode "query_by=title" \
    --data-urlencode "prioritize_exact_match=true" \
    -H "X-TYPESENSE-API-KEY: xyz" | jq '{
      results: [.hits[] | {
        id: .document.id,
        title: .document.title,
        text_match: .text_match,
        best_field_score: .text_match_info.best_field_score,
        tokens_matched: .text_match_info.tokens_matched
      }]
    }'

echo ""
echo "=== With prioritize_token_position=true ==="
curl -s "$TYPESENSE_HOST/collections/events/documents/search" -G \
    --data-urlencode "q=Florida State at Florida" \
    --data-urlencode "query_by=title" \
    --data-urlencode "prioritize_exact_match=true" \
    --data-urlencode "prioritize_token_position=true" \
    -H "X-TYPESENSE-API-KEY: xyz" | jq '{
      results: [.hits[] | {
        id: .document.id,
        title: .document.title,
        text_match: .text_match,
        best_field_score: .text_match_info.best_field_score,
        tokens_matched: .text_match_info.tokens_matched
      }]
    }'

docker stop typesense-repro && docker rm typesense-repro
