import os
import sys
import django
import logging
from datetime import datetime

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

from django.db import connection
from django.contrib.auth.models import Group
from users.models import CustomUser, Branch

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

def fix_report_schedules_recipients_table():
    """Fix the report_schedules_recipients table column name"""
    try:
        logger.info("Step 1: Fixing report_schedules_recipients table...")
        
        with connection.cursor() as cursor:
            # Check if table exists
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.tables 
                WHERE table_schema = DATABASE() 
                AND table_name = 'report_schedules_recipients'
            """)
            
            if cursor.fetchone()[0] == 0:
                logger.info("Creating report_schedules_recipients table with correct structure...")
                cursor.execute("""
                    CREATE TABLE `report_schedules_recipients` (
                        `id` bigint(20) NOT NULL AUTO_INCREMENT,
                        `reportschedule_id` char(32) NOT NULL,
                        `customuser_id` char(32) NOT NULL,
                        PRIMARY KEY (`id`),
                        UNIQUE KEY `report_schedules_recipients_unique` (`reportschedule_id`, `customuser_id`),
                        KEY `report_schedules_recipients_reportschedule_id_idx` (`reportschedule_id`),
                        KEY `report_schedules_recipients_customuser_id_idx` (`customuser_id`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                """)
                logger.info("✅ Created report_schedules_recipients table")
            else:
                # Check current column structure
                cursor.execute("""
                    SELECT COLUMN_NAME 
                    FROM information_schema.columns 
                    WHERE table_schema = DATABASE() 
                    AND table_name = 'report_schedules_recipients'
                """)
                columns = [row[0] for row in cursor.fetchall()]
                logger.info(f"Current columns: {columns}")
                
                if 'user_id' in columns and 'customuser_id' not in columns:
                    logger.info("Renaming user_id to customuser_id...")
                    cursor.execute("""
                        ALTER TABLE report_schedules_recipients 
                        CHANGE COLUMN user_id customuser_id char(32) NOT NULL
                    """)
                    logger.info("✅ Renamed user_id to customuser_id")
                elif 'customuser_id' in columns:
                    logger.info("✅ customuser_id column already exists")
                else:
                    logger.info("Adding customuser_id column...")
                    cursor.execute("""
                        ALTER TABLE report_schedules_recipients 
                        ADD COLUMN customuser_id char(32) NOT NULL
                    """)
                    logger.info("✅ Added customuser_id column")
        
        logger.info("✅ Fix report_schedules_recipients table completed")
        return True
        
    except Exception as e:
        logger.error(f"❌ Error fixing report_schedules_recipients table: {e}")
        return False

def test_client_creation_final():
    """Final test of client creation"""
    try:
        logger.info("Step 2: Final client creation test...")
        
        # Test phone number
        test_phone = "+254712345999"
        
        # Check if user already exists
        if CustomUser.objects.filter(phone_number=test_phone).exists():
            logger.info("Test user already exists, deleting...")
            CustomUser.objects.filter(phone_number=test_phone).delete()
        
        # Get default branch
        branch = Branch.objects.filter(is_active=True).first()
        if not branch:
            logger.error("No active branch found")
            return False
        
        # Create test user
        user = CustomUser.objects.create_user(
            username=test_phone,
            phone_number=test_phone,
            first_name="Test",
            last_name="Final",
            role='borrower',
            branch=branch
        )
        
        logger.info(f"✅ Created test user: {user.get_full_name()}")
        logger.info(f"✅ User ID: {user.id}, Branch: {user.branch.name}")
        
        # Test group assignment
        clients_group = Group.objects.get_or_create(name='Clients')[0]
        user.groups.add(clients_group)
        logger.info("✅ Group assignment successful")
        
        # Clean up test user
        user.delete()
        logger.info("✅ Test user cleaned up")
        
        logger.info("✅ Final client creation test completed")
        return True
        
    except Exception as e:
        logger.error(f"❌ Final client creation test failed: {e}")
        return False

def main():
    """Main execution function"""
    logger.info("=" * 80)
    logger.info("FINAL REPORT SCHEDULES FIX - Complete Django Fix")
    logger.info("=" * 80)
    
    steps_completed = 0
    steps_failed = 0
    
    # Step 1: Fix report_schedules_recipients table
    if fix_report_schedules_recipients_table():
        steps_completed += 1
    else:
        steps_failed += 1
    
    logger.info("")
    
    # Step 2: Final client creation test
    if test_client_creation_final():
        steps_completed += 1
    else:
        steps_failed += 1
    
    # Final summary
    logger.info("")
    logger.info("=" * 80)
    logger.info("FINAL SUMMARY")
    logger.info("=" * 80)
    logger.info(f"Completed {steps_completed}/2 steps successfully")
    
    if steps_failed > 0:
        logger.info(f"⚠️  {steps_failed} steps failed")
    else:
        logger.info("🎉 ALL ISSUES RESOLVED!")
        logger.info("")
        logger.info("Your Django system is now fully functional:")
        logger.info("1. ✅ Auth tables fixed")
        logger.info("2. ✅ Group assignments working")
        logger.info("3. ✅ Client creation working")
        logger.info("4. ✅ Report schedules table fixed")
    
    logger.info("")
    logger.info("Next steps:")
    logger.info("1. Test client creation in your Django admin")
    logger.info("2. Verify that all features are working properly")
    logger.info("3. The 'phone number already registered' error should be resolved")
    
    logger.info("")
    logger.info("=" * 80)
    logger.info("SCRIPT COMPLETED")
    logger.info("=" * 80)

if __name__ == "__main__":
    main()