from lawrisk.utils.env_loader import load_env
load_env()

from lawrisk.services.licensing_repo import _lic_pg_conn
import json

def check_duplicate_permits():
    with _lic_pg_conn() as conn:
        cur = conn.cursor()
        
        print("--- Duplicate Permit Names ---")
        cur.execute("""
            SELECT name, COUNT(*)
            FROM permits
            GROUP BY name
            HAVING COUNT(*) > 1
        """)
        dupes = cur.fetchall()
        print(f"Duplicate permit names total: {len(dupes)}")
        for d in dupes:
            print(f" Name: {d[0]}, Count: {d[1]}")

        print("\n--- Permits with same name in same region ---")
        cur.execute("""
            SELECT p.name, rpd.region_id, COUNT(*)
            FROM region_permit_details rpd
            JOIN permits p ON p.id = rpd.permit_id
            GROUP BY p.name, rpd.region_id
            HAVING COUNT(*) > 1
        """)
        dupes_reg = cur.fetchall()
        print(f"Permits with same name in same region: {len(dupes_reg)}")
        for d in dupes_reg:
            print(f" Name: {d[0]}, Region: {d[1]}, Count: {d[2]}")

if __name__ == "__main__":
    check_duplicate_permits()
