# Docker Deployment Testing Guide

## Prerequisites

1. **Start Docker Desktop**
   - Open Docker Desktop application on your Mac
   - Wait for it to fully start (green indicator in menu bar)
   - Verify with: `docker --version`

## Step 1: Clean Slate

Remove any existing containers and volumes:

```bash
docker compose down -v
```

## Step 2: Build Images

Build fresh Docker images with all blockchain integration:

```bash
docker compose build --no-cache
```

This will:
- Build backend image with Python dependencies
- Build frontend image with npm dependencies
- Include all blockchain integration code

**Expected time**: 3-5 minutes

## Step 3: Start Services

Start both backend and frontend containers:

```bash
docker compose up -d
```

The `-d` flag runs containers in detached mode (background).

## Step 4: Monitor Startup

Watch logs to see when services are ready:

```bash
# Watch all logs
docker compose logs -f

# Or watch specific service
docker compose logs -f backend
docker compose logs -f frontend
```

**Wait for these messages:**
- Backend: `Uvicorn running on http://0.0.0.0:8000`
- Frontend: `➜  Local:   http://localhost:5173/`

Press `Ctrl+C` to stop watching logs.

## Step 5: Verify Services

Check that containers are running:

```bash
docker compose ps
```

Expected output:
```
NAME                          STATUS              PORTS
h2h-prototype-backend-1       Up X minutes        0.0.0.0:8000->8000/tcp
h2h-prototype-frontend-1      Up X minutes        0.0.0.0:5173->5173/tcp
```

## Step 6: Health Checks

### Backend API Test

```bash
# Test auth endpoint
curl -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "alice@example.com", "password": "password123"}'
```

**Expected**: JSON with `access_token` and `refresh_token`

### Frontend Test

```bash
# Check frontend is serving
curl -s http://localhost:5173 | grep -o "<title>.*</title>"
```

**Expected**: `<title>H2H - Peer-to-Peer Betting Platform</title>`

## Step 7: Database Initialization

Initialize the database with seed data:

```bash
docker compose exec backend python seed_data.py
```

**Expected**: Creates test users (alice, bob, charlie) with sample bets

## Step 8: Verify Blockchain Files

Check that blockchain integration files are present in containers:

```bash
# Check backend blockchain services
docker compose exec backend ls -la app/blockchain/services/

# Check frontend blockchain components
docker compose exec frontend ls -la src/blockchain/hooks/
```

## Step 9: Test Application in Browser

Open your browser and navigate to:

### Frontend
**URL**: http://localhost:5173

**Test these features:**
1. Login with `alice@example.com` / `password123`
2. Navigate to Marketplace
3. Look for blockchain badges (⛓️) on bet cards
4. Click "Create Bet" and check for gas estimate panel
5. Check header for "Connect Wallet" button
6. Navigate to Wallet page
7. Verify "On-Chain Escrow" section appears

### Backend API Docs
**URL**: http://localhost:8000/docs

Browse the interactive API documentation (Swagger UI)

## Step 10: Run Automated Tests

Run the verification script inside the container:

```bash
# Copy verification script into backend container
docker compose exec backend bash -c "cat > /tmp/verify.sh << 'EOF'
#!/bin/bash
echo '🔍 Verifying Blockchain Integration in Docker'
echo '=============================================='

FILES=(
  'app/blockchain/contracts/BetEscrow.pseudocode.md'
  'app/blockchain/contracts/BetOracle.pseudocode.md'
  'app/blockchain/services/blockchain_service.py'
  'app/blockchain/services/blockchain_indexer.py'
  'app/blockchain/services/oracle_node.py'
)

PASSED=0
FAILED=0

for file in \"\${FILES[@]}\"; do
  if [ -f \"\$file\" ]; then
    echo \"✅ \$file\"
    ((PASSED++))
  else
    echo \"❌ \$file\"
    ((FAILED++))
  fi
done

echo ''
echo \"Results: \$PASSED passed, \$FAILED failed\"
EOF
chmod +x /tmp/verify.sh && /tmp/verify.sh"
```

## Step 11: Check Logs for Errors

```bash
# Check for any errors in backend
docker compose logs backend | grep -i error

# Check for any errors in frontend
docker compose logs frontend | grep -i error
```

**Expected**: No critical errors (warnings about blockchain providers are OK)

## Step 12: Interactive Testing

### Open a shell in backend container

```bash
docker compose exec backend bash
```

Inside the container:
```bash
# Check Python can import blockchain modules
python -c "from app.blockchain.services.blockchain_service import BlockchainService; print('✅ Blockchain imports work')"

# Check database has blockchain fields
python -c "from app.models.bet import Bet; import inspect; fields = [f for f in dir(Bet) if 'blockchain' in f]; print(f'Blockchain fields: {fields}')"

# Exit container
exit
```

### Open a shell in frontend container

```bash
docker compose exec frontend sh
```

Inside the container:
```bash
# Check TypeScript compiles without errors
npm run type-check 2>&1 | grep -E '(error|✓)' || echo "Type check completed"

# Exit container
exit
```

## Step 13: Performance Check

Monitor resource usage:

```bash
docker stats --no-stream
```

**Expected**:
- Backend: < 200MB RAM
- Frontend: < 500MB RAM (during development)

## Step 14: Stop Services

When done testing:

```bash
# Stop containers (keep data)
docker compose stop

# Or stop and remove containers (keep volumes)
docker compose down

# Or remove everything including volumes
docker compose down -v
```

## Troubleshooting

### Port Already in Use

```bash
# Kill processes on port 8000
lsof -ti:8000 | xargs kill -9

# Kill processes on port 5173
lsof -ti:5173 | xargs kill -9

# Then restart
docker compose up -d
```

### Frontend Build Errors

```bash
# Rebuild frontend without cache
docker compose build --no-cache frontend
docker compose up -d frontend
```

### Backend Import Errors

```bash
# Rebuild backend
docker compose build --no-cache backend
docker compose exec backend pip install -r requirements.txt
docker compose restart backend
```

### Database Issues

```bash
# Reset database
docker compose down -v
docker compose up -d
docker compose exec backend python seed_data.py
```

### View Container File System

```bash
# Backend files
docker compose exec backend ls -R app/blockchain/

# Frontend files
docker compose exec frontend find src/blockchain -type f
```

## Complete Test Script

Save this as `test-docker.sh`:

```bash
#!/bin/bash

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

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

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

# Build images
echo "🏗️  Building Docker images..."
docker compose build --no-cache > /dev/null 2>&1
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✅ Images built successfully${NC}"
else
  echo -e "${RED}❌ Image build failed${NC}"
  exit 1
fi

# 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

# Wait for services to be ready
echo "⏳ Waiting for services to be ready (15 seconds)..."
sleep 15

# Check backend
echo "🔍 Testing backend..."
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}"
else
  echo -e "${RED}❌ Backend not responding (HTTP $BACKEND_STATUS)${NC}"
fi

# 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}"
else
  echo -e "${RED}❌ Frontend not responding (HTTP $FRONTEND_STATUS)${NC}"
fi

# Seed database
echo "🌱 Seeding database..."
docker compose exec -T backend python seed_data.py > /dev/null 2>&1
echo -e "${GREEN}✅ Database seeded${NC}"

# Test login
echo "🔐 Testing login endpoint..."
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 successful${NC}"
else
  echo -e "${RED}❌ Login failed${NC}"
fi

echo ""
echo "=============================="
echo "🎉 Docker deployment test complete!"
echo ""
echo "Access the application:"
echo "  Frontend: http://localhost:5173"
echo "  Backend API: http://localhost:8000/docs"
echo ""
echo "To view logs: docker compose logs -f"
echo "To stop: docker compose down"
```

Make executable and run:
```bash
chmod +x test-docker.sh
./test-docker.sh
```

## Expected Results

✅ **All checks should pass:**
- Images build successfully
- Both containers start and run
- Backend API responds on port 8000
- Frontend serves on port 5173
- Login endpoint works
- Database seeds successfully
- Blockchain files present in containers
- No critical errors in logs

## Success Criteria

Your Docker deployment is successful if:

1. ✅ `docker compose ps` shows both containers "Up"
2. ✅ Can login at http://localhost:5173 with test credentials
3. ✅ Backend API docs accessible at http://localhost:8000/docs
4. ✅ Blockchain badges visible in UI (⛓️)
5. ✅ Connect Wallet button appears in header
6. ✅ Gas estimate panels show in bet creation
7. ✅ No import/module errors in logs

## Next Steps

Once Docker deployment is verified:
1. Test full bet lifecycle in browser
2. Verify all blockchain UI components render
3. Check browser console for any React errors
4. Test WebSocket connections (real-time updates)
5. Verify responsive design on mobile viewport

The application is now running in Docker with full blockchain integration! 🚀
