#!/bin/bash

# Script to start Blockscout container and build assets
# Run from VMID 5000 or Proxmox host

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Start Blockscout and Build Assets"
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 current container status
echo "=== Step 1: Checking container status ==="
BLOCKSCOUT_CONTAINER=$($EXEC_PREFIX docker ps -a | grep blockscout | grep -v postgres | awk '{print $1}' | head -1)

if [ -z "$BLOCKSCOUT_CONTAINER" ]; then
    echo "❌ Blockscout container not found"
    echo "You may need to start it with docker-compose:"
    echo "  cd /opt/blockscout && docker compose up -d blockscout"
    exit 1
fi

echo "Found container: $BLOCKSCOUT_CONTAINER"
CONTAINER_STATUS=$($EXEC_PREFIX docker inspect --format='{{.State.Status}}' $BLOCKSCOUT_CONTAINER)
echo "Container status: $CONTAINER_STATUS"
echo ""

# Step 2: Start container if not running
if [ "$CONTAINER_STATUS" != "running" ]; then
    echo "=== Step 2: Starting Blockscout container ==="
    $EXEC_PREFIX docker start $BLOCKSCOUT_CONTAINER
    echo "Waiting for container to start..."
    sleep 5
    
    # Verify it started
    CONTAINER_STATUS=$($EXEC_PREFIX docker inspect --format='{{.State.Status}}' $BLOCKSCOUT_CONTAINER)
    if [ "$CONTAINER_STATUS" != "running" ]; then
        echo "❌ Container failed to start"
        echo "Check logs: docker logs $BLOCKSCOUT_CONTAINER"
        exit 1
    fi
    echo "✅ Container started"
else
    echo "=== Step 2: Container already running ==="
    echo "✅ Container is running"
fi
echo ""

# Step 3: Wait for Blockscout to be ready
echo "=== Step 3: Waiting for Blockscout to initialize ==="
echo "This may take 30-60 seconds..."
for i in {1..12}; do
    if $EXEC_PREFIX docker exec $BLOCKSCOUT_CONTAINER pgrep -f "beam.smp" >/dev/null 2>&1; then
        echo "✅ Blockscout process detected"
        break
    fi
    echo "Waiting... ($i/12)"
    sleep 5
done
echo ""

# Step 4: Build static assets
echo "=== Step 4: Building static assets ==="
echo "Running mix phx.digest..."
if $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER mix phx.digest 2>&1; then
    echo "✅ Assets built successfully"
else
    echo "⚠️  mix phx.digest failed, trying alternative method..."
    # Try alternative
    $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER npm run deploy 2>&1 || \
    $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER bin/blockscout eval "Mix.Tasks.Phx.Digest.run([])" 2>&1 || {
        echo "❌ Failed to build assets"
        echo "You may need to build assets manually or check container logs"
    }
fi
echo ""

# Step 5: Verify assets
echo "=== Step 5: Verifying assets ==="
if $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER test -f priv/static/cache_manifest.json 2>/dev/null; then
    echo "✅ cache_manifest.json exists"
    $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER ls -lh priv/static/cache_manifest.json
else
    echo "❌ cache_manifest.json still missing"
    echo "Assets may need to be built manually or container may need restart"
fi
echo ""

# Step 6: Check container health
echo "=== Step 6: Checking container health ==="
$EXEC_PREFIX docker ps | grep blockscout
echo ""

# Step 7: Check recent logs
echo "=== Step 7: Recent logs ==="
$EXEC_PREFIX docker logs $BLOCKSCOUT_CONTAINER 2>&1 | tail -20
echo ""

echo "=========================================="
echo "✅ Process complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "  1. Verify Blockscout is responding: curl http://localhost:4000/api/v2/stats"
echo "  2. Check logs if issues: docker logs blockscout"
echo "  3. Ensure docker-compose has correct startup command"
echo ""

