from lawrisk.utils.env_loader import load_env
load_env()

from lawrisk.services.licensing_repo import load_permits_and_risks, _lic_pg_conn
import json

def test_bound_permit_risks():
    with _lic_pg_conn() as conn:
        cur = conn.cursor()
        cur.execute("SELECT id FROM regions WHERE name = '市级'")
        rid = str(cur.fetchone()[0])
        # Find a permit that I bound themes to
        cur.execute("SELECT id, name FROM permits WHERE name = '旅馆业特种行业许可证核发'")
        p_row = cur.fetchone()
        if not p_row:
            print("Permit not found")
            return
        pid = str(p_row[0])
        p_name = p_row[1]

    print(f"Testing Permit: {p_name} ({pid})")
    results = load_permits_and_risks(rid, None, pid)
    
    if results:
        p_data = results[0]
        print(f"Themes Count: {len(p_data.get('themes', []))}")
        print(f"Risks returned: {len(p_data.get('risks', []))}")
        # Check for actual duplicates in the list
        risk_ids = [r['id'] for r in p_data.get('risks', [])]
        unique_risk_ids = set(risk_ids)
        print(f"Unique risk IDs: {len(unique_risk_ids)}")
        if len(risk_ids) > len(unique_risk_ids):
            print("DUPLICATES DETECTED!")
    else:
        print("No results.")

if __name__ == "__main__":
    test_bound_permit_risks()
