#!/usr/bin/env python3
"""Database Connection Health Monitor"""
import sys
import time
from postgresql_models import engine, SessionLocal, Song, Profile, Plan

def check_connection_pool():
    """Check database connection pool health"""
    pool = engine.pool
    print(f"📊 Connection Pool Status:")
    print(f"   Size: {pool.size()}")
    print(f"   Checked out: {pool.checkedout()}")
    print(f"   Overflow: {pool.overflow()}")
    print(f"   Checked in: {pool.checkedin()}")
    return pool.checkedout() < (pool.size() + pool.overflow()) * 0.8

def test_query_performance():
    """Test basic query performance"""
    db = SessionLocal()
    try:
        start = time.time()
        count = db.query(Song).count()
        duration = time.time() - start
        print(f"\n⚡ Query Performance:")
        print(f"   Song count: {count}")
        print(f"   Duration: {duration:.3f}s")
        return duration < 0.5  # Should be under 500ms
    finally:
        db.close()

def main():
    print("🔍 Database Health Check\n")
    
    try:
        # Test connection
        conn = engine.connect()
        conn.close()
        print("✅ Database connection: OK\n")
        
        # Check pool
        pool_ok = check_connection_pool()
        
        # Test queries
        query_ok = test_query_performance()
        
        if pool_ok and query_ok:
            print("\n✅ All checks passed")
            return 0
        else:
            print("\n⚠️  Some checks failed")
            return 1
            
    except Exception as e:
        print(f"\n❌ Health check failed: {e}")
        return 2

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