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 delete_permit_by_name(permit_name):
    load_env()
    conn = lic_repo._lic_pg_conn()
    cur = conn.cursor()

    try:
        print(f"Searching for permit: {permit_name}")
        cur.execute("SELECT id FROM permits WHERE name = %s", (permit_name,))
        row = cur.fetchone()
        
        if not row:
            print(f"Permit '{permit_name}' not found.")
            return

        permit_id = row[0]
        print(f"Found permit ID: {permit_id}")

        # List of tables to clean up that reference permit_id
        # Based on licensing_repo.py structures
        tables = [
            "region_permit_risks",
            "region_permit_scopes",
            "region_permit_subitems",
            "region_permit_details",
            "region_theme_permits",
            "region_permit_theme_overrides", # Might not exist or might be empty, but good to try
            "permit_sources"
        ]

        for table in tables:
            try:
                # Check if table exists first to avoid crashing on optional tables
                cur.execute(f"SELECT to_regclass('{table}')")
                if cur.fetchone()[0]:
                    print(f"Cleaning table: {table}")
                    cur.execute(f"DELETE FROM {table} WHERE permit_id = %s", (permit_id,))
                    print(f"  Deleted {cur.rowcount} rows.")
                else:
                     print(f"Table {table} does not exist, skipping.")
            except Exception as e:
                print(f"Error cleaning {table}: {e}")
                # Don't abort, try next table

        # Finally delete from permits
        print("Deleting from permits table...")
        cur.execute("DELETE FROM permits WHERE id = %s", (permit_id,))
        print(f"Deleted {cur.rowcount} rows from permits.")
        
        conn.commit()
        print(f"Successfully deleted permit '{permit_name}' and likely associated data.")

    except Exception as e:
        conn.rollback()
        print(f"An error occurred: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    delete_permit_by_name("食品小作坊登记证")
