#!/usr/bin/env python
"""Simple database connection test"""
import os
import sys

# Add project root to path
project_root = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, project_root)

try:
    import pg8000
    print("pg8000 module installed: OK")
except ImportError:
    print("pg8000 module NOT installed. Run: pip install pg8000")
    sys.exit(1)

# Load .env
env_config = {}
env_file = '.env'
if os.path.exists(env_file):
    with open(env_file, 'r') as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith('#') and '=' in line:
                key, value = line.split('=', 1)
                env_config[key] = value

print("\nDatabase Configuration:")
print(f"  Host: {env_config.get('LIC_PG_HOST')}")
print(f"  Port: {env_config.get('LIC_PG_PORT')}")
print(f"  User: {env_config.get('LIC_PG_USER')}")
print(f"  Database: {env_config.get('LIC_PG_DATABASE')}")
print(f"  Password: {'*' * len(env_config.get('LIC_PG_PASSWORD', ''))}")

# Test connection
try:
    print("\nTesting connection...")
    conn = pg8000.connect(
        host=env_config.get('LIC_PG_HOST'),
        port=int(env_config.get('LIC_PG_PORT', '5432')),
        user=env_config.get('LIC_PG_USER'),
        password=env_config.get('LIC_PG_PASSWORD'),
        database=env_config.get('LIC_PG_DATABASE')
    )
    cursor = conn.cursor()
    cursor.execute("SELECT version();")
    version = cursor.fetchone()[0]
    print(f"Connection successful! DB Version: {version[:50]}")
    conn.close()
    print("\nYou can now run the migration:")
    print("  python run_migration.py")
except Exception as e:
    print(f"\nConnection failed: {e}")
    print("\nPlease check:")
    print("1. Database server is running")
    print("2. Network is accessible")
    print("3. Username/password is correct")
    print("4. Firewall is not blocking")
