#!/bin/bash
#
# Debug why BP102 mapping isn't being applied
#
set -e

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

echo "=========================================="
echo "Debugging BP102 Mapping Issue"
echo "=========================================="
echo ""

echo "✅ WORKING: PL689, PL6204, PL12321"
echo "❌ NOT WORKING: BP102, PL11089"
echo ""

echo "1️⃣ Checking if BP102 is in CORRECT_FILE_MAPPING..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

grep -A5 "'BP102'" /home/plagis/workspace/plagis_aumentum/aumentum_browser_service.py | head -7

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "2️⃣ Testing BP102 with verbose logging..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Clear cache
rm -f /tmp/aumentum_pdfs/BP102*.pdf

# Make sure server is running
if ! curl -s "http://localhost:8001/health" > /dev/null 2>&1; then
    echo "❌ Server not running. Starting it..."
    cd /home/plagis/workspace/plagis_aumentum
    source venv/bin/activate
    python3 aumentum_api.py > /tmp/bp102_debug.log 2>&1 &
    sleep 8
fi

echo "Server is running. Testing BP102..."
echo ""

# Test BP102
curl -v "http://localhost:8001/documents/pdf-by-document-number?document_number=BP102&document_id=10000000014368" \
  -o /tmp/BP102_debug.pdf 2>&1 | grep -E "(< HTTP|< X-)"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "3️⃣ Checking what was generated..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

if [ -f /tmp/BP102_debug.pdf ]; then
    file_type=$(file /tmp/BP102_debug.pdf)
    size=$(stat -c%s /tmp/BP102_debug.pdf 2>/dev/null || stat -f%z /tmp/BP102_debug.pdf)
    
    echo "File: /tmp/BP102_debug.pdf"
    echo "Type: $file_type"
    echo "Size: $size bytes"
    echo ""
    
    if file /tmp/BP102_debug.pdf | grep -q "PDF"; then
        echo "✅ PDF generated!"
        echo ""
        echo "Opening for verification..."
        xdg-open /tmp/BP102_debug.pdf &
        sleep 2
        
        echo ""
        read -p "What document number does the PDF show? " bp102_shows
        
        if [ "$bp102_shows" = "BP102" ]; then
            echo ""
            echo "🎉 BP102 IS WORKING!"
            echo "   The mapping was applied correctly."
        else
            echo ""
            echo "❌ BP102 shows: $bp102_shows"
            echo "   The mapping was NOT applied or used wrong file."
            echo ""
            echo "Expected URL: store://2015/3/17/10/10/879dcd53-f552-4e82-858f-7e868e60a275.bin"
            echo "This file should contain BP102 content (based on manual verification)"
        fi
    else
        echo "❌ Not a PDF - error occurred"
        cat /tmp/BP102_debug.pdf
    fi
else
    echo "❌ File not created"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "4️⃣ Checking server logs for BP102..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Find latest log file
log_file=$(ls -t /tmp/api*.log /tmp/bp102_debug.log /tmp/server.log 2>/dev/null | head -1)

if [ -f "$log_file" ]; then
    echo "Checking: $log_file"
    echo ""
    echo "Looking for 'APPLYING FILE URL FIX for BP102'..."
    echo ""
    
    if grep -q "APPLYING FILE URL FIX for BP102" "$log_file"; then
        echo "✅ FOUND! Mapping was applied:"
        grep -A5 "APPLYING FILE URL FIX for BP102" "$log_file" | tail -6
    else
        echo "❌ NOT FOUND! Mapping was NOT applied"
        echo ""
        echo "Possible causes:"
        echo "  1. BP102 key doesn't match exactly in dictionary"
        echo "  2. Code not reloaded"
        echo "  3. Logic error in mapping application"
        echo ""
        echo "Showing recent BP102 related logs:"
        grep -i "bp102" "$log_file" | tail -20
    fi
else
    echo "No log file found. Server might be in foreground."
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "5️⃣ Testing direct Python function..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

cd /home/plagis/workspace/plagis_aumentum
source venv/bin/activate

python3 << 'PYTHON_EOF'
from aumentum_browser_service import AumentumBrowserService, DEFAULT_DB_CONFIG, DEFAULT_CONTENTSTORE_BASE

service = AumentumBrowserService(DEFAULT_DB_CONFIG, DEFAULT_CONTENTSTORE_BASE)

print("Testing BP102 directly in Python...")
print("")

# Check if BP102 is in mapping
if 'BP102' in service.CORRECT_FILE_MAPPING:
    print("✅ BP102 IS in CORRECT_FILE_MAPPING")
    print(f"   URL: {service.CORRECT_FILE_MAPPING['BP102']['correct_url']}")
else:
    print("❌ BP102 NOT in CORRECT_FILE_MAPPING")
    print("   Available keys:", list(service.CORRECT_FILE_MAPPING.keys()))

print("")

# Try to resolve
result = service.resolve_store_urls_by_document_number('BP102')

if result and len(result) > 0:
    print(f"✅ Resolved {len(result)} document groups")
    print(f"   First group has {len(result[0]['images'])} images")
    if result[0]['images']:
        print(f"   First image URL: {result[0]['images'][0]['content_url']}")
else:
    print("❌ No results returned")
PYTHON_EOF

echo ""
echo "=========================================="
echo "Summary"
echo "=========================================="
echo ""
echo "Based on diagnostics above:"
echo "  1. Is BP102 in CORRECT_FILE_MAPPING? (check output above)"
echo "  2. Is mapping being applied? (check for '🔄 APPLYING FILE URL FIX')"
echo "  3. What URL is being used? (check image URL)"
echo ""

