
from lawrisk.services import licensing_repo as lic_repo
from lawrisk.utils.env_loader import load_env
import time

def kill_all():
    load_env()
    try:
        conn = lic_repo._lic_pg_conn()
        cur = conn.cursor()
        
        # Get all active PIDs
        cur.execute("""
            SELECT pid, state, query 
            FROM pg_stat_activity 
            WHERE datname = 'licensing_risks' 
            AND pid <> pg_backend_pid()
        """)
        rows = cur.fetchall()
        
        for pid, state, query in rows:
            print(f"Killing PID {pid} [{state}]: {query[:50] if query else 'None'}...")
            cur2 = conn.cursor()
            try:
                cur2.execute("SELECT pg_terminate_backend(%s)", (pid,))
                print(f"  Result: {cur2.fetchone()[0]}")
            except Exception as e:
                print(f"  Failed: {e}")
        
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    kill_all()
