
import os
import pg8000
import sys

def load_env(env_path='.env'):
    config = {}
    if not os.path.exists(env_path):
        # try parent
        env_path = os.path.join('..', '.env')
        if not os.path.exists(env_path):
            print(f"Warning: {env_path} not found")
            return config
        
    with open(env_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if '=' in line:
                key, value = line.split('=', 1)
                config[key.strip()] = value.strip()
    return config

def inspect_remote_db():
    config = load_env()
    
    with open('remote_inspection_output.txt', 'w', encoding='utf-8') as f:
        def log(msg):
            print(msg)
            f.write(str(msg) + "\n")

        log("\nConnecting to licensing_risks database...")
        try:
            conn = pg8000.connect(
                user=config.get('LIC_PG_USER', 'postgres'),
                password=config.get('LIC_PG_PASSWORD'),
                host=config.get('LIC_PG_HOST', 'localhost'),
                port=int(config.get('LIC_PG_PORT', 5432)),
                database=config.get('LIC_PG_DATABASE', 'licensing_risks')
            )
            log("✅ Connection successful!")
            
            cursor = conn.cursor()
            
            log("\n--- Listing Tables ---\n")
            cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")
            tables = cursor.fetchall()
            for table in tables:
                log(table[0])
                
            log("\n--- Checking Users/Accounts ---\n")
            log("Found table: auth_users")
            cursor.execute(f"SELECT * FROM auth_users") # Get all users to find the specific one
            users = cursor.fetchall()
            for user in users:
                log(user)
                
            # Print columns
            cursor.execute(f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'auth_users'")
            cols = cursor.fetchall()
            log("\nColumns:")
            for col in cols:
                log(col)
    
            conn.close()
            
        except Exception as e:
            log(f"❌ Database error: {e}")

if __name__ == "__main__":
    inspect_remote_db()
