
import sys
import os
import psycopg2

# 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 rename_permit(permit_id, new_name):
    load_env()
    
    if hasattr(lic_repo, "_lic_pg_conn"):
        conn_func = getattr(lic_repo, "_lic_pg_conn")
    else:
        print("Could not find connection function")
        return

    try:
        conn = conn_func()
    except Exception as e:
        print(f"Error connecting to DB: {e}")
        return

    try:
        cur = conn.cursor()
        
        # Verify existence
        cur.execute("SELECT name FROM permits WHERE id = %s", (permit_id,))
        row = cur.fetchone()
        if not row:
            print(f"Permit with ID {permit_id} not found.")
            return
            
        old_name = row[0]
        print(f"Renaming permit {permit_id}:")
        print(f"  Old Name: {old_name}")
        print(f"  New Name: {new_name}")
        
        # Check if new name exists
        cur.execute("SELECT id FROM permits WHERE name = %s", (new_name,))
        if cur.fetchone():
            print(f"Error: A permit with the name '{new_name}' already exists.")
            return

        # Update
        cur.execute("UPDATE permits SET name = %s WHERE id = %s", (new_name, permit_id))
        conn.commit()
        print("Successfully renamed.")
        
    except Exception as e:
        conn.rollback()
        print(f"Error updating permit: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python rename_permit.py <permit_id> <new_name>")
    else:
        pid = sys.argv[1]
        nname = sys.argv[2]
        rename_permit(pid, nname)
