import sys
import os
import json

try:
    import psycopg2
    DATABASE_URL = "postgresql://postgres:CiBjh6LM7Yuqkq-jo2r7eQDw@postgresql-genesis-u50607.vm.elestio.app:25432/postgres"
    conn = psycopg2.connect(DATABASE_URL)
    cur = conn.cursor()
    
    print("=== RLM INFRASTRUCTURE AUDIT ===")
    
    cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'aiva_rlm' AND table_type = 'BASE TABLE';")
    tables = cur.fetchall()
    print(f"Tables in aiva_rlm: {[t[0] for t in tables]}")
    
    for table in tables:
        t_name = table[0]
        try:
            cur.execute(f"SELECT COUNT(*) FROM aiva_rlm.{t_name};")
            count = cur.fetchone()[0]
            print(f" - {t_name}: {count} rows")
        except Exception as te:
            conn.rollback()
            print(f" - {t_name}: Error reading count: {te}")
        
    # Check views
    print("\nChecking RLM Views:")
    cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'aiva_rlm' AND table_type = 'VIEW';")
    views = cur.fetchall()
    for view in views:
        v_name = view[0]
        try:
            cur.execute(f"SELECT * FROM aiva_rlm.{v_name} LIMIT 1;")
            res = cur.fetchone()
            print(f" - {v_name}: Active")
        except:
            conn.rollback()
            print(f" - {v_name}: Error or empty")

    cur.close()
    conn.close()
except Exception as e:
    print(f"Error auditing RLM DB: {e}")
