#!/bin/bash
#
# Analyze the association chain using API endpoints
# This works even if Python database libraries aren't available locally
#
set -e

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

echo "=========================================="
echo "Association Chain Analysis via API"
echo "=========================================="
echo ""

docs=("PL11089" "PL689" "BP102" "PL6204" "PL12321")

echo "Analyzing 5 documents in the suspected chain..."
echo ""

# Create output file
output="/tmp/chain_analysis.txt"
> "$output"

echo "Document Association Analysis" >> "$output"
echo "Generated: $(date)" >> "$output"
echo "=" >> "$output"
echo "" >> "$output"

for doc in "${docs[@]}"; do
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Checking: $doc"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Use the debug endpoint to get raw database info
    response=$(curl -s "$API_BASE/debug/document-numbers?search_pattern=${doc}" 2>/dev/null)
    
    if echo "$response" | jq -e '.documents' > /dev/null 2>&1; then
        echo "Database records:"
        echo "$response" | jq -r '.documents[] | "  ID: \(.id), Number: \"\(.document_number)\", Length: \(.length), Visual: \(.visual_representation)"'
        
        # Save to file
        echo "" >> "$output"
        echo "$doc:" >> "$output"
        echo "$response" | jq -r '.documents[] | "  ID: \(.id), Number: \"\(.document_number)\", HasWhitespace: \(.has_leading_space or .has_trailing_space)"' >> "$output"
    else
        echo "  ❌ Not found or error"
    fi
    
    echo ""
done

echo "=========================================="
echo "Summary saved to: $output"
echo "=========================================="
cat "$output"

echo ""
echo "=========================================="
echo "Next: Create Mapping Table"
echo "=========================================="
echo ""

echo "Based on your manual verification:"
echo ""
echo "| Document | Node ID | Tagged As | Actually Shows | File URL |"
echo "|----------|---------|-----------|----------------|----------|"
echo "| ???      | ???     | PL11089   | PL689          | store://2015/3/26/... |"
echo "| ???      | ???     | PL689     | BP102          | store://2015/3/17/... |"
echo "| ???      | ???     | BP102     | PL6204         | ???                   |"
echo "| ???      | ???     | PL6204    | PL12321        | ???                   |"
echo "| ???      | ???     | PL12321   | ???            | ???                   |"
echo ""
echo "We need to fill in this table to create the fix."

