#!/usr/bin/env python3
"""Check if Redis is running and accessible."""
import sys
import subprocess

try:
    import redis
    from config import Config
except ImportError as e:
    print(f'❌ Required module not available: {e}')
    # Fallback to process check
    try:
        result = subprocess.run(['pgrep', 'redis-server'], capture_output=True, text=True)
        if result.returncode == 0:
            print('✅ Redis server process found (could not verify connection)')
            sys.exit(0)
        else:
            print('❌ No Redis server process found')
            sys.exit(1)
    except Exception as e:
        print(f'❌ Error checking Redis process: {e}')
        sys.exit(1)

# Load configuration
from config import REDIS_URL

# Parse REDIS_URL from configuration
redis_url = REDIS_URL

# Extract host, port, db from URL
try:
    # Parse redis://host:port/db format
    url = redis_url.replace('redis://', '')
    host_port_db = url.split('/')
    host_port = host_port_db[0].split(':')
    host = host_port[0]
    port = int(host_port[1]) if len(host_port) > 1 else 6379
    db = int(host_port_db[1]) if len(host_port_db) > 1 else 0
except:
    host, port, db = 'localhost', 6379, 0

# If we get here, redis is available
try:
    r = redis.Redis(host=host, port=port, db=db)
    r.ping()
    print(f'✅ Redis is running and accessible at {redis_url}')
    sys.exit(0)
except redis.ConnectionError as e:
    print(f'❌ Redis connection failed: {e}')
    print(f'   Tried connecting to: {redis_url}')
    sys.exit(1)
except Exception as e:
    print(f'❌ Redis error: {e}')
    sys.exit(1)
