
import pg8000.dbapi as pg
import os

def list_unbound():
    conn_params = {
        "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"),
    }
    
    try:
        conn = pg.connect(**conn_params)
        cur = conn.cursor()
        
        print("--- Unbound Permits (市级) ---")
        cur.execute("""
            SELECT p.name
            FROM region_permit_details rpd
            JOIN permits p ON p.id = rpd.permit_id
            JOIN regions r ON r.id = rpd.region_id
            LEFT JOIN region_theme_permits rtp ON rtp.permit_id = rpd.permit_id AND rtp.region_id = rpd.region_id
            WHERE r.name = '市级' AND rtp.permit_id IS NULL
            ORDER BY p.name
        """)
        rows = cur.fetchall()
        for i, row in enumerate(rows):
            print(f"{i+1}. {row[0]}")
            
        conn.close()
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    list_unbound()
