import sys
import os

# Init path to allow importing lawrisk
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from lawrisk.services import licensing_repo as lic_repo
from lawrisk.utils.env_loader import load_env

def find_permit():
    load_env()
    
    # Try to access _lic_pg_conn, handle if it's not directly exposed or named differently
    if hasattr(lic_repo, "_lic_pg_conn"):
        conn_func = getattr(lic_repo, "_lic_pg_conn")
    elif hasattr(lic_repo, "get_connection"):
        conn_func = getattr(lic_repo, "get_connection") 
    else:
        # Fallback to looking for connection logic inside licensing_repo (it might be a context manager)
        # But for now assume _lic_pg_conn exists as per audit_risks.py
        conn_func = lic_repo._lic_pg_conn

    # Check if it returns a connection or context manager
    # _lic_pg_conn in licensing_repo seems to be a context manager based on 'with _lic_pg_conn() as conn'
    # But audit_risks.py calls it as 'conn = lic_repo._lic_pg_conn()' ?
    # Let's check audit_risks.py again.
    # Line 17: conn = lic_repo._lic_pg_conn()
    # Line 94: conn.close()
    # This implies it returns a connection object, not a context manager.
    # But licensing_repo.py line 778 says: 'with _lic_pg_conn() as conn:' ...
    # This means _lic_pg_conn() can be used as a context manager OR returns something that has __enter__.
    # A standard pg8000 connection can be used as a context manager.
    
    try:
        conn = conn_func()
    except Exception as e:
        print(f"Error connecting to DB: {e}")
        return

    cur = conn.cursor()
    
    if len(sys.argv) > 1:
        permit_name = sys.argv[1]
    else:
        permit_name = "仅销售预包装食品备案登记"
    print(f"Searching for permit: {permit_name}")

    # Check strict match
    cur.execute("SELECT id, name FROM permits WHERE name = %s", (permit_name,))
    strict_match = cur.fetchone()
    
    if strict_match:
        print(f"Found EXACT match: ID={strict_match[0]}, Name={strict_match[1]}")
        permit_id = strict_match[0]
        
        # Check regions
        cur.execute("""
            SELECT r.name 
            FROM region_theme_permits rtp
            JOIN regions r ON r.id = rtp.region_id
            WHERE rtp.permit_id = %s
            GROUP BY r.name
        """, (permit_id,))
        regions = cur.fetchall()
        if regions:
            print("Bind to regions:")
            for r_name in regions:
                print(f"  - {r_name[0]}")
        else:
            print("No region bindings found.")

        # Check risks
        cur.execute("""
            SELECT count(*) FROM region_permit_risks WHERE permit_id = %s
        """, (permit_id,))
        risk_count_row = cur.fetchone()
        risk_count = risk_count_row[0] if risk_count_row else 0
        print(f"Total risk entries: {risk_count}")
        
    else:
        print("No exact match found.")
        
    # Check fuzzy match
    print("\nChecking fuzzy matches...")
    cur.execute("SELECT id, name FROM permits WHERE name ILIKE %s", (f"%{permit_name}%",))
    fuzzy_matches = cur.fetchall()
    
    if fuzzy_matches:
        for mid, mname in fuzzy_matches:
             if strict_match and mid == strict_match[0]:
                 continue
             print(f"Found partial match: ID={mid}, Name={mname}")
    else:
        if not strict_match:
            print("No fuzzy matches found.")

    conn.close()

if __name__ == "__main__":
    find_permit()
