#!/usr/bin/env python3
"""
Quick DB connection tester - run on the server to verify credentials.
Usage: python test_db_connection.py
"""
import os
import sys

# Load .env first
try:
    from dotenv import load_dotenv
    load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env'), override=True)
    print("Loaded .env")
except ImportError:
    print("WARNING: python-dotenv not available")

db_name = os.getenv('DB_NAME', 'NOT SET')
db_user = os.getenv('DB_USER', 'NOT SET')
db_pass = os.getenv('DB_PASSWORD', 'NOT SET')
db_host = os.getenv('DB_HOST', 'localhost')
db_port = int(os.getenv('DB_PORT', '3306'))

print(f"\nCredentials from .env:")
print(f"  DB_NAME     = {db_name}")
print(f"  DB_USER     = {db_user}")
print(f"  DB_PASSWORD = {db_pass[:3]}{'*' * (len(db_pass)-3) if len(db_pass) > 3 else '***'}")
print(f"  DB_HOST     = {db_host}")
print(f"  DB_PORT     = {db_port}")

# Try connecting
try:
    import pymysql
    print(f"\nAttempting connection...")
    conn = pymysql.connect(
        host=db_host,
        port=db_port,
        user=db_user,
        password=db_pass,
        database=db_name,
        connect_timeout=10,
    )
    with conn.cursor() as c:
        c.execute("SELECT VERSION()")
        version = c.fetchone()[0]
        c.execute("SELECT DATABASE()")
        current_db = c.fetchone()[0]
        c.execute("SELECT USER()")
        current_user = c.fetchone()[0]
    conn.close()
    print(f"\n  SUCCESS - Connected!")
    print(f"  MySQL version : {version}")
    print(f"  Connected as  : {current_user}")
    print(f"  Database      : {current_db}")
except Exception as e:
    print(f"\n  FAILED: {e}")
    print("\nTroubleshooting:")
    print("  1045 = wrong password OR user not granted access to this database")
    print("  2003 = can't reach host (wrong host/port)")
    print("  1049 = database doesn't exist")
    print("\nTo reset the password in cPanel:")
    print("  cPanel -> MySQL Databases -> MySQL Users -> Change Password")
    print(f"  Set a new password for user: {db_user}")
    print("  Then update DB_PASSWORD in your .env file on the server")
    sys.exit(1)
