#!/usr/bin/env python
"""
Import all users from Grazuri database (user table) into Haven Grazuri system
"""
import os
import django
import sys
import base64
from datetime import datetime
import warnings

# Suppress warnings
warnings.filterwarnings('ignore')

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from users.models import CustomUser, Branch
from django.db import connection, transaction
from django.contrib.auth.hashers import make_password

def import_grazuri_users():
    """Import users from the Grazuri 'user' table"""
    
    print("=" * 80)
    print("Importing Users from Grazuri Database")
    print("=" * 80)
    
    # Get main branch
    main_branch = Branch.objects.filter(code='MAIN').first()
    if not main_branch:
        print("❌ Main branch not found. Please create it first.")
        return
    
    # Map Grazuri roles to Haven Grazuri roles
    role_mapping = {
        'admin': 'admin',
        'Admin': 'admin',
        'Credit Controller': 'loan_officer',
        'Loan Officer': 'loan_officer',
        'Team Leader': 'team_leader',
        'Secretary': 'secretary',
        'Auditor': 'auditor',
        'Manager': 'team_leader',
    }
    
    imported_count = 0
    skipped_count = 0
    updated_count = 0
    
    with connection.cursor() as cursor:
        # Check if user table exists
        cursor.execute("SHOW TABLES LIKE 'user'")
        if not cursor.fetchone():
            print("❌ Grazuri 'user' table not found in database")
            return
        
        # Fetch all users from Grazuri user table
        cursor.execute("""
            SELECT userid, name, email, gender, id_number, phone, addr1, addr2, 
                   district, country, comment, username, password, role, 
                   date_of_birth, passport, branch
            FROM user
            ORDER BY userid
        """)
        
        grazuri_users = cursor.fetchall()
        print(f"\nFound {len(grazuri_users)} users in Grazuri database\n")
        
        with transaction.atomic():
            for row in grazuri_users:
                (userid, name, email, gender, id_number, phone, addr1, addr2,
                 district, country, comment, username, password_encoded, role,
                 date_of_birth, passport, branch_code) = row
                
                # Skip if username already exists
                if CustomUser.objects.filter(username=username).exists():
                    user = CustomUser.objects.get(username=username)
                    print(f"⚠ User '{username}' already exists - skipping")
                    skipped_count += 1
                    continue
                
                # Parse name
                name_parts = name.strip().split() if name else ['User', str(userid)]
                first_name = name_parts[0] if len(name_parts) > 0 else 'User'
                last_name = ' '.join(name_parts[1:]) if len(name_parts) > 1 else str(userid)
                
                # Map role
                haven_role = role_mapping.get(role, 'borrower')
                
                # Decode password (Grazuri uses base64 encoding)
                try:
                    decoded_password = base64.b64decode(password_encoded).decode('utf-8') if password_encoded else 'ChangeMe@2025'
                except:
                    decoded_password = 'ChangeMe@2025'
                
                # Clean phone number
                clean_phone = phone.strip() if phone else f'+254{userid}'
                if not clean_phone.startswith('+'):
                    if clean_phone.startswith('0'):
                        clean_phone = '+254' + clean_phone[1:]
                    elif clean_phone.startswith('254'):
                        clean_phone = '+' + clean_phone
                    else:
                        clean_phone = '+254' + clean_phone
                
                # Clean email
                clean_email = email.strip() if email and '@' in email else f'{username}@havengrazuri.co.ke'
                
                # Check if email already exists
                if CustomUser.objects.filter(email=clean_email).exists():
                    clean_email = f'{username}_{userid}@havengrazuri.co.ke'
                
                # Check if phone already exists
                if CustomUser.objects.filter(phone_number=clean_phone).exists():
                    clean_phone = f'+254{userid}{str(userid)[-4:]}'
                
                # Clean ID number
                clean_id = str(id_number) if id_number else str(userid)
                if CustomUser.objects.filter(id_number=clean_id).exists():
                    clean_id = f'{clean_id}_{userid}'
                
                # Parse gender
                gender_map = {'Male': 'M', 'Female': 'F', 'M': 'M', 'F': 'F'}
                clean_gender = gender_map.get(gender, 'M') if gender else 'M'
                
                # Determine if staff
                is_staff = haven_role in ['admin', 'team_leader', 'loan_officer', 'secretary', 'auditor']
                is_superuser = haven_role == 'admin'
                
                try:
                    # Create user
                    user = CustomUser.objects.create(
                        username=username,
                        email=clean_email,
                        first_name=first_name[:30],
                        last_name=last_name[:150],
                        role=haven_role,
                        phone_number=clean_phone,
                        id_number=clean_id,
                        date_of_birth=date_of_birth if date_of_birth else None,
                        gender=clean_gender,
                        branch=main_branch,
                        is_staff=is_staff,
                        is_superuser=is_superuser,
                        status='active',
                        is_active=True,
                    )
                    
                    # Set password
                    user.set_password(decoded_password)
                    user.save()
                    
                    # Set accessible branches for staff
                    if is_staff:
                        if is_superuser:
                            user.accessible_branches.set(Branch.objects.all())
                        else:
                            user.accessible_branches.set([main_branch])
                    
                    print(f"✓ Imported: {name} ({username}) - Role: {haven_role}")
                    imported_count += 1
                    
                except Exception as e:
                    print(f"❌ Error importing {username}: {str(e)}")
                    skipped_count += 1
                    continue
    
    print("\n" + "=" * 80)
    print("Import Summary")
    print("=" * 80)
    print(f"✓ Successfully imported: {imported_count} users")
    print(f"⚠ Skipped (already exist): {skipped_count} users")
    print(f"Total processed: {imported_count + skipped_count}")
    print("=" * 80)
    
    if imported_count > 0:
        print("\n📝 NOTE: All imported users have their original passwords from Grazuri")
        print("   If password doesn't work, default password is: ChangeMe@2025")
        print("\n🔐 SECURITY: Please ask users to change their passwords on first login")

if __name__ == '__main__':
    try:
        import_grazuri_users()
    except Exception as e:
        print(f"\n❌ Error: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
