
import os
import pg8000
import sys

def load_env(env_path='.env'):
    config = {}
    if not os.path.exists(env_path):
        env_path = os.path.join('..', '.env')
        if not os.path.exists(env_path):
            print(f"Warning: {env_path} not found")
            return config
        
    with open(env_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if '=' in line:
                key, value = line.split('=', 1)
                config[key.strip()] = value.strip()
    return config

def run_migration():
    config = load_env()
    print("\nConnecting to licensing_risks database...")
    
    conn = None
    try:
        conn = pg8000.connect(
            user=config.get('LIC_PG_USER', 'postgres'),
            password=config.get('LIC_PG_PASSWORD'),
            host=config.get('LIC_PG_HOST', 'localhost'),
            port=int(config.get('LIC_PG_PORT', 5432)),
            database=config.get('LIC_PG_DATABASE', 'licensing_risks')
        )
        print("✅ Connection successful!")
        cursor = conn.cursor()

        # IDs identified
        theme_id = 'fc4b7e18-de60-4f58-9805-bac84097c00e'
        unique_permit_id = 'fd21d74d-0626-46a3-9f98-e0658d2ca206' # 印章刻制业许可证核发
        
        print("\n--- Starting Deletion Process ---\n")

        # 1. Delete Theme Association
        print(f"Deleting associations for theme {theme_id}...")
        cursor.execute("DELETE FROM region_theme_permits WHERE theme_id = %s", (theme_id,))
        print(f"Deleted rows from region_theme_permits.")

        # 2. Delete Theme
        print(f"Deleting theme {theme_id}...")
        cursor.execute("DELETE FROM themes WHERE id = %s", (theme_id,))
        print(f"Deleted row from themes.")

        # 3. Delete Unique Permit and its details
        print(f"Deleting unique permit {unique_permit_id} (印章刻制业许可证核发)...")
        
        tables_to_clean = [
            'region_permit_details',
            'region_permit_risks',
            'region_permit_scopes',
            'region_permit_subitems'
        ]
        
        for table in tables_to_clean:
            print(f"Cleaning {table}...")
            cursor.execute(f"DELETE FROM {table} WHERE permit_id = %s", (unique_permit_id,))
        
        print(f"Deleting permit from permits table...")
        cursor.execute("DELETE FROM permits WHERE id = %s", (unique_permit_id,))
        
        # Commit transaction
        conn.commit()
        print("\n✅ Migration completed successfully and committed.")

    except Exception as e:
        print(f"\n❌ Database error: {e}")
        if conn:
            conn.rollback()
            print("Transaction rolled back.")
    finally:
        if conn:
            conn.close()

if __name__ == "__main__":
    run_migration()
