"""
Test script to verify the development environment setup.
"""

import sys
import time
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

try:
    from config.settings import database, redis, app, okx, dashboard
    print("✅ Configuration module loaded successfully")
except ImportError as e:
    print(f"❌ Failed to load configuration: {e}")
    sys.exit(1)


def test_database_connection():
    """Test database connection."""
    print("\n🔍 Testing database connection...")
    
    try:
        import psycopg2
        from psycopg2 import sql
        
        conn_params = {
            "host": database.host,
            "port": database.port,
            "database": database.database,
            "user": database.user,
            "password": database.password,
        }
        
        print(f"Connecting to: {database.host}:{database.port}/{database.database}")
        
        conn = psycopg2.connect(**conn_params)
        cursor = conn.cursor()
        
        # Test basic query
        cursor.execute("SELECT version();")
        version = cursor.fetchone()[0]
        print(f"✅ Database connected successfully")
        print(f"   PostgreSQL version: {version}")
        
        # Test if we can create tables
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS test_table (
                id SERIAL PRIMARY KEY,
                name VARCHAR(100),
                created_at TIMESTAMP DEFAULT NOW()
            );
        """)
        
        cursor.execute("INSERT INTO test_table (name) VALUES ('test_setup');")
        conn.commit()
        
        cursor.execute("SELECT COUNT(*) FROM test_table;")
        count = cursor.fetchone()[0]
        print(f"✅ Database operations successful (test records: {count})")
        
        # Clean up test table
        cursor.execute("DROP TABLE IF EXISTS test_table;")
        conn.commit()
        
        cursor.close()
        conn.close()
        
    except ImportError:
        print("❌ psycopg2 not installed, run: uv sync")
        return False
    except Exception as e:
        print(f"❌ Database connection failed: {e}")
        return False
    
    return True


def test_redis_connection():
    """Test Redis connection."""
    print("\n🔍 Testing Redis connection...")
    
    try:
        import redis as redis_module
        
        r = redis_module.Redis(
            host=redis.host,
            port=redis.port,
            password=redis.password,
            decode_responses=True
        )
        
        # Test basic operations
        r.set("test_key", "test_value")
        value = r.get("test_key")
        
        if value == "test_value":
            print("✅ Redis connected successfully")
            print(f"   Connected to: {redis.host}:{redis.port}")
            
            # Clean up
            r.delete("test_key")
            return True
        else:
            print("❌ Redis test failed")
            return False
            
    except ImportError:
        print("❌ redis not installed, run: uv sync")
        return False
    except Exception as e:
        print(f"❌ Redis connection failed: {e}")
        return False


def test_configuration():
    """Test configuration loading."""
    print("\n🔍 Testing configuration...")
    
    print(f"Database URL: {database.connection_url}")
    print(f"Redis URL: {redis.connection_url}")
    print(f"Dashboard: {dashboard.host}:{dashboard.port}")
    print(f"Environment: {app.environment}")
    print(f"OKX configured: {okx.is_configured}")
    
    if not okx.is_configured:
        print("⚠️  OKX API not configured (update .env file)")
    
    return True


def test_directories():
    """Test required directories exist."""
    print("\n🔍 Testing directory structure...")
    
    required_dirs = [
        "config",
        "config/bot_configs",
        "database",
        "scripts",
        "tests",
    ]
    
    all_exist = True
    for dir_name in required_dirs:
        dir_path = project_root / dir_name
        if dir_path.exists():
            print(f"✅ {dir_name}/ exists")
        else:
            print(f"❌ {dir_name}/ missing")
            all_exist = False
    
    return all_exist


def main():
    """Run all tests."""
    print("🧪 Running setup verification tests...")
    print(f"Project root: {project_root}")
    
    tests = [
        ("Configuration", test_configuration),
        ("Directories", test_directories),
        ("Database", test_database_connection),
        ("Redis", test_redis_connection),
    ]
    
    results = []
    
    for test_name, test_func in tests:
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"❌ {test_name} test crashed: {e}")
            results.append((test_name, False))
    
    print("\n📊 Test Results:")
    print("=" * 40)
    
    all_passed = True
    for test_name, passed in results:
        status = "✅ PASS" if passed else "❌ FAIL"
        print(f"{test_name:15} {status}")
        if not passed:
            all_passed = False
    
    print("=" * 40)
    
    if all_passed:
        print("🎉 All tests passed! Environment is ready.")
        return 0
    else:
        print("⚠️  Some tests failed. Check the setup.")
        return 1


if __name__ == "__main__":
    sys.exit(main()) 