from lawrisk.utils.env_loader import load_env
load_env()

import os
import pg8000.dbapi as pg

def get_conn():
    host = os.getenv("LIC_PG_HOST", "172.24.240.1")
    port = int(os.getenv("LIC_PG_PORT", os.getenv("PG_PORT", "5432")))
    user = os.getenv("LIC_PG_USER", os.getenv("PG_USER", "postgres"))
    password = os.getenv("LIC_PG_PASSWORD", "")
    database = os.getenv("LIC_PG_DATABASE", "licensing_risks")
    return pg.connect(host=host, port=port, user=user, password=password, database=database)

def list_risks_for_one_permit():
    conn = get_conn()
    cur = conn.cursor()
    
    # Let's pick a permit that HAS risks
    cur.execute("""
        SELECT p.name, p.id, COUNT(rpr.risk_id)
        FROM permits p
        JOIN region_permit_risks rpr ON rpr.permit_id = p.id
        GROUP BY p.name, p.id
        ORDER BY COUNT(rpr.risk_id) DESC
        LIMIT 5
    """)
    top_permits = cur.fetchall()
    
    for p_name, p_id, count in top_permits:
        print(f"\n=== Permit: {p_name} ({p_id}) | Total Risks: {count} ===")
        cur.execute("""
            SELECT rpr.serial_number, rk.risk_content, rk.id
            FROM region_permit_risks rpr
            JOIN risks rk ON rk.id = rpr.risk_id
            WHERE rpr.permit_id = %s
            ORDER BY rpr.serial_number, rk.risk_content
        """, (p_id,))
        risks = cur.fetchall()
        for r in risks:
            sn, content, rid = r
            print(f" [{sn}] {rid} | {repr(content[:100])}")
            
    conn.close()

if __name__ == "__main__":
    list_risks_for_one_permit()
