#!/usr/bin/env python3
"""
Manual Fix Steps for User Permissions Database Issue

This script provides step-by-step commands to fix the database issue manually.
Run each step one by one.

Usage:
    python manual_fix_steps.py
"""

import os
import sys

def setup_django():
    """Setup Django environment"""
    try:
        import django
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        django.setup()
        print("[SUCCESS] Django environment setup successful")
        return True
    except Exception as e:
        print(f"[ERROR] Django setup failed: {str(e)}")
        return False

def step1_merge_migrations():
    """Step 1: Merge conflicting migrations"""
    print("\n" + "="*60)
    print("STEP 1: MERGE CONFLICTING MIGRATIONS")
    print("="*60)
    print("Run this command:")
    print("python manage.py makemigrations --merge users")
    print("\nThis will resolve the migration conflicts.")
    
    input("Press Enter after running the command above...")

def step2_create_migrations():
    """Step 2: Create missing migrations"""
    print("\n" + "="*60)
    print("STEP 2: CREATE MISSING MIGRATIONS")
    print("="*60)
    print("Run this command:")
    print("python manage.py makemigrations users")
    print("\nThis will create any missing migrations for the UserPermission model.")
    
    input("Press Enter after running the command above...")

def step3_apply_migrations():
    """Step 3: Apply migrations"""
    print("\n" + "="*60)
    print("STEP 3: APPLY MIGRATIONS")
    print("="*60)
    print("Run this command:")
    print("python manage.py migrate users")
    print("\nThis will apply all migrations and create/update the user_permissions table.")
    
    input("Press Enter after running the command above...")

def step4_verify_fix():
    """Step 4: Verify the fix"""
    print("\n" + "="*60)
    print("STEP 4: VERIFY THE FIX")
    print("="*60)
    
    if not setup_django():
        return False
    
    try:
        from django.db import connection
        with connection.cursor() as cursor:
            # Try to query the table with the module column
            cursor.execute("SELECT COUNT(*) FROM user_permissions WHERE module = 'test'")
            result = cursor.fetchone()
            print("[SUCCESS] user_permissions table is working correctly!")
            print("The database fix is complete.")
            return True
    except Exception as e:
        print(f"[ERROR] Verification failed: {str(e)}")
        print("The table might still need fixes. Check the error message above.")
        return False

def main():
    """Main function"""
    print("="*80)
    print("MANUAL FIX STEPS FOR USER PERMISSIONS DATABASE ISSUE")
    print("="*80)
    print("This script will guide you through fixing the database issue step by step.")
    print("Follow each step carefully.")
    
    # Step 1: Merge migrations
    step1_merge_migrations()
    
    # Step 2: Create migrations
    step2_create_migrations()
    
    # Step 3: Apply migrations
    step3_apply_migrations()
    
    # Step 4: Verify fix
    if step4_verify_fix():
        print("\n" + "="*80)
        print("FIX COMPLETED SUCCESSFULLY!")
        print("="*80)
        print("The user_permissions table should now work correctly.")
        print("You can now access the user permissions page without errors.")
        print("The permission-based navigation system will also work as expected.")
    else:
        print("\n" + "="*80)
        print("FIX INCOMPLETE")
        print("="*80)
        print("There may still be issues. Please check the error messages above.")
        print("You may need to run additional Django commands or check the database manually.")
    
    print("\nNext steps:")
    print("1. Test the user permissions page")
    print("2. Try checking/unchecking permissions")
    print("3. Verify that navigation items show/hide based on permissions")

if __name__ == '__main__':
    main()
