#!/bin/bash

# Script to diagnose and fix Blockscout database connection issue
# Blockscout can't see tables even though they exist

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Blockscout Database Connection Fix"
echo "=========================================="
echo ""

# Check if running from Proxmox host or inside container
if [ -f "/proc/1/cgroup" ] && grep -q "lxc" /proc/1/cgroup 2>/dev/null; then
    EXEC_PREFIX=""
    echo "Running inside VMID 5000"
else
    EXEC_PREFIX="pct exec $VMID --"
    echo "Running from Proxmox host, executing in VMID 5000"
fi

# Step 1: Check what database Blockscout is connecting to
echo "=== Step 1: Checking Blockscout DATABASE_URL ==="
BLOCKSCOUT_CONTAINER=$($EXEC_PREFIX docker ps -a | grep blockscout | grep -v postgres | awk '{print $1}' | head -1)
if [ -n "$BLOCKSCOUT_CONTAINER" ]; then
    DATABASE_URL=$($EXEC_PREFIX docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' $BLOCKSCOUT_CONTAINER | grep "^DATABASE_URL=" | cut -d= -f2-)
    echo "Blockscout DATABASE_URL: $DATABASE_URL"
    
    # Extract components
    DB_USER=$(echo "$DATABASE_URL" | sed -n 's|.*://\([^:]*\):.*|\1|p')
    DB_PASS=$(echo "$DATABASE_URL" | sed -n 's|.*://[^:]*:\([^@]*\)@.*|\1|p')
    DB_HOST=$(echo "$DATABASE_URL" | sed -n 's|.*@\([^:]*\):.*|\1|p')
    DB_PORT=$(echo "$DATABASE_URL" | sed -n 's|.*@[^:]*:\([^/]*\)/.*|\1|p')
    DB_NAME=$(echo "$DATABASE_URL" | sed -n 's|.*/\([^?]*\).*|\1|p')
    
    echo "  User: $DB_USER"
    echo "  Host: $DB_HOST"
    echo "  Port: $DB_PORT"
    echo "  Database: $DB_NAME"
else
    echo "❌ Blockscout container not found"
    exit 1
fi
echo ""

# Step 2: Verify tables exist in that specific database
echo "=== Step 2: Verifying tables in database '$DB_NAME' ==="
$EXEC_PREFIX docker exec blockscout-postgres psql -U "$DB_USER" -d "$DB_NAME" -c "
SELECT 
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'migrations_status') 
    THEN '✅ migrations_status' ELSE '❌ migrations_status MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'blocks') 
    THEN '✅ blocks' ELSE '❌ blocks MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'transactions') 
    THEN '✅ transactions' ELSE '❌ transactions MISSING' END;
" 2>&1

echo ""

# Step 3: Check current search_path for that database
echo "=== Step 3: Checking search_path ==="
$EXEC_PREFIX docker exec blockscout-postgres psql -U "$DB_USER" -d "$DB_NAME" -c "SHOW search_path;" 2>&1

echo ""

# Step 4: Test query from Blockscout's perspective
echo "=== Step 4: Testing query from Blockscout container ==="
if $EXEC_PREFIX docker start $BLOCKSCOUT_CONTAINER 2>/dev/null; then
    sleep 5
    echo "Attempting to query from Blockscout..."
    $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER bin/blockscout eval "
      IO.puts(\"Testing database connection...\")
      case Explorer.Repo.query(\"SELECT current_database(), current_schema()\") do
        {:ok, %{rows: [[db, schema]]}} -> 
          IO.puts(\"✅ Connected to database: #{db}, schema: #{schema}\")
        error -> 
          IO.puts(\"❌ Connection error: #{inspect(error)}\")
      end
      
      IO.puts(\"\\nTesting migrations_status table...\")
      case Explorer.Repo.query(\"SELECT COUNT(*) FROM migrations_status\") do
        {:ok, %{rows: [[count]]}} -> 
          IO.puts(\"✅ migrations_status accessible, count: #{count}\")
        {:error, error} -> 
          IO.puts(\"❌ Cannot access migrations_status: #{inspect(error)}\")
      end
    " 2>&1 | head -20 || echo "⚠️  Cannot query from container"
else
    echo "⚠️  Cannot start container for testing"
fi

echo ""

# Step 5: Check if there are multiple databases
echo "=== Step 5: Checking for multiple databases ==="
$EXEC_PREFIX docker exec blockscout-postgres psql -U blockscout -d postgres -c "\l" 2>&1 | grep -E "Name|blockscout" | head -5

echo ""

# Step 6: Verify connection string format
echo "=== Step 6: Recommended Fix ==="
echo "If Blockscout can't see tables, try:"
echo ""
echo "1. Ensure DATABASE_URL is correct in docker-compose.yml:"
echo "   DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout"
echo ""
echo "2. Run migrations in a one-off container:"
echo "   docker run --rm --network container:$BLOCKSCOUT_CONTAINER \\"
echo "     -e DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout \\"
echo "     blockscout/blockscout:latest \\"
echo "     bin/blockscout eval 'Explorer.Release.migrate()'"
echo ""
echo "3. Update docker-compose.yml to run migrations before start:"
echo "   command: sh -c \"bin/blockscout eval 'Explorer.Release.migrate()' && bin/blockscout start\""


