
import os
import pg8000.dbapi as pg
from lawrisk.utils.env_loader import load_env

def list_db_permits():
    load_env()
    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()
        
        with open("current_permits.txt", "w", encoding="utf-8") as f:
            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
                WHERE r.name = '市级'
                ORDER BY p.name
            """)
            print("Writing permits to current_permits.txt...")
            for row in cur.fetchall():
                f.write(row[0] + "\n")
        
        conn.close()
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    list_db_permits()
