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_dupes_in_output():
    with _lic_pg_conn() as conn:
        cur = conn.cursor()
        cur.execute("SELECT id FROM regions WHERE name = '市级'")
        rid = str(cur.fetchone()[0])
        
    # Get all permits for this region
    all_permits = load_permits_and_risks(rid)
    
    dupe_found = False
    for p in all_permits:
        risks = p.get("risks", [])
        risk_contents = [r["risk_content"] for r in risks]
        risk_serials = [r["serial_number"] for r in risks if r["serial_number"]]
        
        if len(risk_contents) != len(set(risk_contents)):
            print(f"DUPE CONTENT in {p['name']}: {len(risk_contents)} total vs {len(set(risk_contents))} unique")
            dupe_found = True
            
        if len(risk_serials) != len(set(risk_serials)):
            print(f"DUPE SERIAL in {p['name']}: {len(risk_serials)} total vs {len(set(risk_serials))} unique")
            dupe_found = True

    if not dupe_found:
        print("No duplicates found in load_permits_and_risks output after fix.")

if __name__ == "__main__":
    test_dupes_in_output()
