#!/usr/bin/env python3
"""
Quick Fix for Table Naming Issue
Fixes the table name mismatch for accessible_branches
"""

import os
import django
from django.db import connection

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

def log_message(message, level='INFO'):
    """Log messages with timestamp"""
    from datetime import datetime
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f"[{timestamp}] {level}: {message}")

def check_table_exists(table_name):
    """Check if a table exists in the database"""
    try:
        with connection.cursor() as cursor:
            cursor.execute(f"""
                SELECT COUNT(*) 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = '{table_name}'
            """)
            return cursor.fetchone()[0] > 0
    except Exception as e:
        log_message(f"Error checking table {table_name}: {e}", 'ERROR')
        return False

def fix_table_naming():
    """Fix the table naming issue"""
    try:
        with connection.cursor() as cursor:
            # Check if the incorrectly named table exists
            if check_table_exists('users_customuser_accessible_branches'):
                log_message("Found users_customuser_accessible_branches table")
                
                # Check if the correctly named table already exists
                if check_table_exists('users_accessible_branches'):
                    log_message("users_accessible_branches already exists, dropping old table")
                    cursor.execute("DROP TABLE users_customuser_accessible_branches")
                else:
                    log_message("Renaming table to correct name...")
                    cursor.execute("""
                        RENAME TABLE users_customuser_accessible_branches 
                        TO users_accessible_branches
                    """)
                    log_message("Table renamed successfully")
            
            elif not check_table_exists('users_accessible_branches'):
                log_message("Creating users_accessible_branches table...")
                cursor.execute("""
                    CREATE TABLE `users_accessible_branches` (
                        `id` bigint(20) NOT NULL AUTO_INCREMENT,
                        `customuser_id` char(32) NOT NULL,
                        `branch_id` char(32) NOT NULL,
                        PRIMARY KEY (`id`),
                        UNIQUE KEY `users_accessible_branches_customuser_id_branch_id_unique` (`customuser_id`, `branch_id`),
                        KEY `users_accessible_branches_branch_id_fk` (`branch_id`),
                        CONSTRAINT `users_accessible_branches_customuser_id_fk` 
                        FOREIGN KEY (`customuser_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
                        CONSTRAINT `users_accessible_branches_branch_id_fk` 
                        FOREIGN KEY (`branch_id`) REFERENCES `users_branch` (`id`) ON DELETE CASCADE
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                """)
                log_message("users_accessible_branches table created successfully")
            else:
                log_message("users_accessible_branches table already exists")
            
            return True
            
    except Exception as e:
        log_message(f"Error fixing table naming: {e}", 'ERROR')
        return False

def verify_fix():
    """Verify the fix"""
    try:
        with connection.cursor() as cursor:
            # Check if the correct table exists
            if check_table_exists('users_accessible_branches'):
                cursor.execute("SELECT COUNT(*) FROM users_accessible_branches")
                count = cursor.fetchone()[0]
                log_message(f"users_accessible_branches table exists with {count} records")
                return True
            else:
                log_message("users_accessible_branches table still doesn't exist", 'ERROR')
                return False
    except Exception as e:
        log_message(f"Verification failed: {e}", 'ERROR')
        return False

def main():
    """Main execution"""
    log_message("=" * 50)
    log_message("FIXING TABLE NAMING ISSUE")
    log_message("=" * 50)
    
    if fix_table_naming():
        if verify_fix():
            log_message("✅ Table naming issue fixed successfully!")
            log_message("Please restart your Django application.")
            return True
        else:
            log_message("❌ Fix verification failed", 'ERROR')
            return False
    else:
        log_message("❌ Failed to fix table naming issue", 'ERROR')
        return False

if __name__ == '__main__':
    import sys
    success = main()
    sys.exit(0 if success else 1)