import os
import sys
import django
from datetime import datetime

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

from django.db import connection
from users.models import CustomUser, Branch
from utils.models import SystemSetting

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

def check_database_state():
    """Check the current state of the database"""
    log_message("=" * 60)
    log_message("DATABASE STATE CHECK")
    log_message("=" * 60)
    
    try:
        # Check branches
        branches = Branch.objects.all()
        active_branches = Branch.objects.filter(is_active=True)
        
        log_message(f"Total branches: {branches.count()}")
        log_message(f"Active branches: {active_branches.count()}")
        
        if active_branches.exists():
            log_message("Active branches:")
            for branch in active_branches:
                log_message(f"  - {branch.name} ({branch.code}) - Main: {branch.is_main_branch}")
        else:
            log_message("❌ NO ACTIVE BRANCHES FOUND - This is the main issue!")
        
        # Check users
        total_users = CustomUser.objects.count()
        borrowers = CustomUser.objects.filter(role='borrower').count()
        users_with_branch = CustomUser.objects.filter(branch__isnull=False).count()
        
        log_message(f"Total users: {total_users}")
        log_message(f"Borrowers: {borrowers}")
        log_message(f"Users with branch: {users_with_branch}")
        
        # Check system settings
        try:
            max_file_size = SystemSetting.get_int('max_file_size_mb', 10)
            log_message(f"Max file size setting: {max_file_size}MB")
        except Exception as e:
            log_message(f"System settings error: {e}")
        
        return active_branches.exists()
        
    except Exception as e:
        log_message(f"Error checking database state: {e}", 'ERROR')
        return False

def create_default_branch():
    """Create a default branch if none exists"""
    try:
        if not Branch.objects.filter(is_active=True).exists():
            log_message("Creating default branch...")
            
            branch = Branch.objects.create(
                name="Main Branch",
                code="MAIN",
                address="Head Office",
                phone_number="+254700000000",
                email="info@branchbusinessadvance.co.ke",
                is_main_branch=True,
                is_active=True
            )
            
            log_message(f"✅ Created default branch: {branch.name}")
            
            # Assign existing users to this branch
            users_without_branch = CustomUser.objects.filter(branch__isnull=True)
            if users_without_branch.exists():
                users_without_branch.update(branch=branch)
                log_message(f"✅ Assigned {users_without_branch.count()} users to default branch")
            
            return True
        else:
            log_message("Active branches already exist")
            return True
            
    except Exception as e:
        log_message(f"Error creating default branch: {e}", 'ERROR')
        return False

def test_client_creation():
    """Test client creation with sample data"""
    try:
        log_message("Testing client creation...")
        
        # Check if we have branches
        active_branches = Branch.objects.filter(is_active=True)
        if not active_branches.exists():
            log_message("❌ Cannot test client creation - no active branches")
            return False
        
        branch = active_branches.first()
        
        # Test data
        test_phone = "+254700123456"
        test_email = "test@example.com"
        
        # Clean up any existing test user
        CustomUser.objects.filter(phone_number=test_phone).delete()
        CustomUser.objects.filter(email=test_email).delete()
        
        # Create test user
        user = CustomUser.objects.create_user(
            username=test_phone,
            email=test_email,
            phone_number=test_phone,
            first_name="Test",
            last_name="User",
            date_of_birth="1990-01-01",
            gender="male",
            id_number="12345678",
            nationality="Kenyan",
            physical_address="Test Address",
            city="Nairobi",
            business_name="Test Business",
            business_type="retail",
            business_address="Test Business Address",
            role='borrower',
            status='active',
            branch=branch
        )
        
        log_message(f"✅ Successfully created test client: {user.get_full_name()}")
        
        # Clean up
        user.delete()
        log_message("✅ Test client cleaned up")
        
        return True
        
    except Exception as e:
        log_message(f"❌ Client creation test failed: {e}", 'ERROR')
        return False

def check_url_patterns():
    """Check if URL patterns are properly configured"""
    try:
        log_message("Checking URL patterns...")
        
        from django.urls import reverse
        
        # Test important URLs
        urls_to_test = [
            'users:client_create',
            'users:client_list',
        ]
        
        for url_name in urls_to_test:
            try:
                url = reverse(url_name)
                log_message(f"✅ {url_name}: {url}")
            except Exception as e:
                log_message(f"❌ {url_name}: {e}", 'ERROR')
        
        return True
        
    except Exception as e:
        log_message(f"Error checking URL patterns: {e}", 'ERROR')
        return False

def main():
    """Main execution function"""
    log_message("CLIENT CREATION DEBUG SCRIPT")
    log_message("=" * 60)
    
    # Step 1: Check database state
    has_branches = check_database_state()
    
    # Step 2: Create default branch if needed
    if not has_branches:
        log_message("\n" + "=" * 60)
        log_message("CREATING DEFAULT BRANCH")
        log_message("=" * 60)
        create_default_branch()
    
    # Step 3: Test client creation
    log_message("\n" + "=" * 60)
    log_message("TESTING CLIENT CREATION")
    log_message("=" * 60)
    test_client_creation()
    
    # Step 4: Check URL patterns
    log_message("\n" + "=" * 60)
    log_message("CHECKING URL PATTERNS")
    log_message("=" * 60)
    check_url_patterns()
    
    # Step 5: Final recommendations
    log_message("\n" + "=" * 60)
    log_message("RECOMMENDATIONS")
    log_message("=" * 60)
    
    active_branches = Branch.objects.filter(is_active=True).count()
    if active_branches > 0:
        log_message("✅ Database setup looks good")
        log_message("\nNext steps:")
        log_message("1. Restart your Django development server")
        log_message("2. Clear browser cache and cookies")
        log_message("3. Try creating a client again")
        log_message("4. Check browser developer console for any JavaScript errors")
        log_message("5. Ensure all form fields are filled correctly")
    else:
        log_message("❌ Still no active branches - manual intervention needed")
    
    log_message("\n" + "=" * 60)
    log_message("DEBUG COMPLETE")
    log_message("=" * 60)

if __name__ == '__main__':
    main()