#!/bin/bash

echo "🐳 H2H Docker Deployment Test"
echo "=============================="
echo ""

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check Docker is running
if ! docker info > /dev/null 2>&1; then
  echo -e "${RED}❌ Docker daemon is not running${NC}"
  echo "Please start Docker Desktop and try again"
  exit 1
fi

echo -e "${GREEN}✅ Docker daemon is running${NC}"
echo ""

# Stop existing containers
echo "🛑 Stopping existing containers..."
docker compose down -v > /dev/null 2>&1

# Build images
echo "🏗️  Building Docker images (this may take 3-5 minutes)..."
docker compose build --no-cache 2>&1 | grep -E '(=>|CACHED|DONE|Successfully)' || true

if [ $? -eq 0 ]; then
  echo -e "${GREEN}✅ Images built successfully${NC}"
else
  echo -e "${RED}❌ Image build failed${NC}"
  exit 1
fi
echo ""

# Start services
echo "🚀 Starting services..."
docker compose up -d

if [ $? -eq 0 ]; then
  echo -e "${GREEN}✅ Services started${NC}"
else
  echo -e "${RED}❌ Failed to start services${NC}"
  exit 1
fi
echo ""

# Wait for services to be ready
echo "⏳ Waiting for services to be ready..."
for i in {1..30}; do
  if curl -s http://localhost:8000/docs > /dev/null 2>&1 && \
     curl -s http://localhost:5173 > /dev/null 2>&1; then
    break
  fi
  echo -n "."
  sleep 1
done
echo ""
echo ""

# Check containers are running
echo "📦 Container Status:"
docker compose ps
echo ""

# Check backend
echo "🔍 Testing backend API..."
BACKEND_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/docs)
if [ "$BACKEND_STATUS" = "200" ]; then
  echo -e "${GREEN}✅ Backend responding (HTTP $BACKEND_STATUS)${NC}"
  echo "   URL: http://localhost:8000/docs"
else
  echo -e "${RED}❌ Backend not responding (HTTP $BACKEND_STATUS)${NC}"
  echo "   Checking logs..."
  docker compose logs --tail=20 backend
fi
echo ""

# Check frontend
echo "🔍 Testing frontend..."
FRONTEND_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:5173)
if [ "$FRONTEND_STATUS" = "200" ]; then
  echo -e "${GREEN}✅ Frontend responding (HTTP $FRONTEND_STATUS)${NC}"
  echo "   URL: http://localhost:5173"
else
  echo -e "${RED}❌ Frontend not responding (HTTP $FRONTEND_STATUS)${NC}"
  echo "   Checking logs..."
  docker compose logs --tail=20 frontend
fi
echo ""

# Seed database
echo "🌱 Seeding database..."
docker compose exec -T backend python seed_data.py > /dev/null 2>&1
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✅ Database seeded with test data${NC}"
  echo "   Users: alice@example.com, bob@example.com, charlie@example.com"
  echo "   Password: password123"
else
  echo -e "${YELLOW}⚠️  Database might already be seeded${NC}"
fi
echo ""

# Test login
echo "🔐 Testing authentication..."
LOGIN_RESPONSE=$(curl -s -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": "password123"}')

if echo "$LOGIN_RESPONSE" | grep -q "access_token"; then
  echo -e "${GREEN}✅ Login endpoint working${NC}"

  # Extract token
  TOKEN=$(echo "$LOGIN_RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])" 2>/dev/null)

  if [ -n "$TOKEN" ]; then
    # Test authenticated endpoint
    echo "🔐 Testing authenticated endpoint..."
    WALLET_RESPONSE=$(curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8000/api/v1/wallet/)

    if echo "$WALLET_RESPONSE" | grep -q "balance"; then
      echo -e "${GREEN}✅ Authenticated endpoints working${NC}"
    fi
  fi
else
  echo -e "${RED}❌ Login failed${NC}"
  echo "Response: $LOGIN_RESPONSE"
fi
echo ""

# Verify blockchain files in containers
echo "⛓️  Checking blockchain integration..."
BACKEND_BLOCKCHAIN=$(docker compose exec -T backend ls app/blockchain/services/ 2>/dev/null | wc -l)
FRONTEND_BLOCKCHAIN=$(docker compose exec -T frontend ls src/blockchain/hooks/ 2>/dev/null | wc -l)

if [ "$BACKEND_BLOCKCHAIN" -gt 3 ]; then
  echo -e "${GREEN}✅ Backend blockchain services present ($BACKEND_BLOCKCHAIN files)${NC}"
else
  echo -e "${RED}❌ Backend blockchain services missing${NC}"
fi

if [ "$FRONTEND_BLOCKCHAIN" -gt 2 ]; then
  echo -e "${GREEN}✅ Frontend blockchain hooks present ($FRONTEND_BLOCKCHAIN files)${NC}"
else
  echo -e "${RED}❌ Frontend blockchain hooks missing${NC}"
fi
echo ""

# Check for errors in logs
echo "📝 Checking logs for errors..."
BACKEND_ERRORS=$(docker compose logs backend 2>&1 | grep -i "error" | grep -v "ERROR_HANDLING" | wc -l)
FRONTEND_ERRORS=$(docker compose logs frontend 2>&1 | grep -i "error" | grep -v "node_modules" | wc -l)

if [ "$BACKEND_ERRORS" -eq 0 ]; then
  echo -e "${GREEN}✅ No backend errors${NC}"
else
  echo -e "${YELLOW}⚠️  Found $BACKEND_ERRORS backend error messages${NC}"
fi

if [ "$FRONTEND_ERRORS" -eq 0 ]; then
  echo -e "${GREEN}✅ No frontend errors${NC}"
else
  echo -e "${YELLOW}⚠️  Found $FRONTEND_ERRORS frontend error messages${NC}"
fi
echo ""

# Summary
echo "=============================="
echo "📊 Test Summary"
echo "=============================="
echo ""
echo "🌐 Access Points:"
echo "   Frontend: http://localhost:5173"
echo "   Backend API Docs: http://localhost:8000/docs"
echo ""
echo "👤 Test Credentials:"
echo "   Email: alice@example.com"
echo "   Password: password123"
echo ""
echo "🔧 Useful Commands:"
echo "   View logs: docker compose logs -f"
echo "   Stop services: docker compose down"
echo "   Restart: docker compose restart"
echo "   Shell access: docker compose exec backend bash"
echo ""

if [ "$BACKEND_STATUS" = "200" ] && [ "$FRONTEND_STATUS" = "200" ]; then
  echo -e "${GREEN}🎉 Docker deployment successful!${NC}"
  echo ""
  echo "Next steps:"
  echo "1. Open http://localhost:5173 in your browser"
  echo "2. Login with test credentials"
  echo "3. Check for blockchain badges (⛓️) in the UI"
  echo "4. Look for 'Connect Wallet' button in header"
  echo "5. Verify gas estimate panels in bet creation"
  exit 0
else
  echo -e "${RED}⚠️  Some services may not be fully ready${NC}"
  echo "Check logs with: docker compose logs -f"
  exit 1
fi
