#!/bin/bash
#
# Quick check to see what PL11089 is returning right now
#
set -e

API_BASE="${API_BASE:-http://localhost:8001}"

echo "=========================================="
echo "Checking Current PL11089 Associations"
echo "=========================================="
echo ""

# Step 1: Query what documents exist for PL11089
echo "1️⃣ Documents in database for PL11089:"
echo "----------------------------"
curl -s "$API_BASE/documents/by-document-number?document_number=PL11089" | jq '.'
echo ""

# Step 2: Try to generate PDF and save
echo "2️⃣ Generating PDF for PL11089:"
echo "----------------------------"
doc_id=$(curl -s "$API_BASE/documents/by-document-number?document_number=PL11089" | jq -r '.items[0].id')

if [ ! -z "$doc_id" ] && [ "$doc_id" != "null" ]; then
    echo "Using Document ID: $doc_id"
    echo ""
    echo "Downloading PDF..."
    curl -v "$API_BASE/documents/pdf-by-document-number?document_number=PL11089&document_id=$doc_id" \
        -o /tmp/PL11089_current_state.pdf 2>&1 | grep -E "(< X-|> HTTP)"
    
    if [ -f /tmp/PL11089_current_state.pdf ]; then
        size=$(stat -c%s /tmp/PL11089_current_state.pdf 2>/dev/null || stat -f%z /tmp/PL11089_current_state.pdf)
        echo ""
        echo "✅ PDF Downloaded: /tmp/PL11089_current_state.pdf"
        echo "   Size: $size bytes"
        echo ""
        echo "📋 MANUALLY CHECK THIS PDF:"
        echo "   xdg-open /tmp/PL11089_current_state.pdf"
        echo ""
        echo "   Look for 'R OF O NO' field on the document"
        echo "   What document number does it show?"
        echo "   - If it shows PL11089 → ✅ Fixed!"
        echo "   - If it shows PL689 → ❌ Workaround not working"  
        echo "   - If it shows BP102 → ❌ Wrong file association"
        echo "   - If it shows something else → ❌ Multiple issues"
    fi
else
    echo "❌ Could not get document ID for PL11089"
fi

echo ""
echo "=========================================="
echo "3️⃣ Check Server Console Output"
echo "=========================================="
echo ""
echo "Look for these messages in the server console:"
echo '  - "📊 Database returned N reference(s)"'
echo '  - "⚠️  APPLYING ASSOCIATION FIX"'
echo '  - "✅ Swapped: store://..."'
echo ""
echo "If you see the swap message but PDF still shows wrong content,"
echo "then the swapped file itself is wrong!"

