# assign_teachers_complete.py
import os
import sys
import django

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()

from staff.models import Staff
from academics.models import SchoolClass, ClassSubject, Subject

def get_or_create_section_subject(section_type):
    """Get or create subject based on section type"""
    subject_map = {
        'english': {
            'name': 'English Section Subjects',
            'code': 'ENG-ALL'
        },
        'french': {
            'name': 'French Section Subjects',
            'code': 'FR-ALL'
        },
        'bilingual': {
            'name': 'Bilingual Section Subjects',
            'code': 'BI-ALL'
        }
    }
    
    data = subject_map.get(section_type, subject_map['bilingual'])
    subject, _ = Subject.objects.get_or_create(
        name=data['name'],
        defaults={
            'code': data['code'],
            'category': 'core'
        }
    )
    return subject

def assign_teacher(teacher_name, class_name, section_type='english'):
    """Assign teacher to class with appropriate section subject"""
    
    # Find teacher
    try:
        name_parts = teacher_name.split()
        if len(name_parts) >= 3 and name_parts[0] in ['Mme', 'Mr.', 'M.']:
            first_name = name_parts[1]
            last_name = ' '.join(name_parts[2:])
        else:
            first_name = name_parts[0]
            last_name = ' '.join(name_parts[1:])
        
        print(f"   Looking for teacher: first_name='{first_name}', last_name='{last_name}'")
        
        teacher = Staff.objects.get(
            user__first_name__icontains=first_name,
            user__last_name__icontains=last_name
        )
        print(f"   ✅ Found teacher: {teacher.user.get_full_name()}")
    except Staff.DoesNotExist:
        print(f"   ❌ Teacher not found: {teacher_name}")
        return False
    except Staff.MultipleObjectsReturned:
        teachers = Staff.objects.filter(
            user__first_name__icontains=first_name,
            user__last_name__icontains=last_name
        )
        teacher = teachers.first()
        print(f"   ⚠️ Multiple found, using: {teacher.user.get_full_name()}")
    except Exception as e:
        print(f"   ❌ Error finding teacher: {e}")
        return False
    
    # Find class
    try:
        school_class = SchoolClass.objects.get(name=class_name)
        print(f"   ✅ Found class: {school_class.name}")
    except SchoolClass.DoesNotExist:
        print(f"   ❌ Class not found: {class_name}")
        return False
    except Exception as e:
        print(f"   ❌ Error finding class: {e}")
        return False
    
    # Get appropriate subject based on section
    subject = get_or_create_section_subject(section_type)
    print(f"   📚 Using subject: {subject.name}")
    
    # Create or update assignment
    try:
        assignment, created = ClassSubject.objects.get_or_create(
            school_class=school_class,
            subject=subject,
            defaults={'teacher': teacher}
        )
        
        if not created and assignment.teacher != teacher:
            assignment.teacher = teacher
            assignment.save()
            print(f"   🔄 Updated: {teacher.user.get_full_name()} → {class_name} ({section_type})")
        elif created:
            print(f"   ✅ Assigned: {teacher.user.get_full_name()} → {class_name} ({section_type})")
        else:
            print(f"   ⏭️ Already assigned: {teacher.user.get_full_name()} → {class_name}")
        
        return True
    except Exception as e:
        print(f"   ❌ Error creating assignment: {e}")
        return False

def main():
    print("=" * 60)
    print("ASSIGNING TEACHERS TO CLASSES")
    print("=" * 60)
    
    # Based on your Excel data
    assignments = [
        # English Section Teachers
        {'teacher_name': 'Mme Shey Annie', 'class_name': 'Class 6', 'section_type': 'english'},
        {'teacher_name': 'Mr. Ndem Gordon', 'class_name': 'Class 5', 'section_type': 'english'},
        {'teacher_name': 'Mr. Nebongo Celestine', 'class_name': 'Class 4', 'section_type': 'english'},
        {'teacher_name': 'Mr. Nebongo Celestine', 'class_name': 'Class 3', 'section_type': 'english'},
        {'teacher_name': 'Mme Nguveha Cecil', 'class_name': 'Class 2', 'section_type': 'english'},
        {'teacher_name': 'Mme Tabi Cynthia', 'class_name': 'Class 2', 'section_type': 'english'},  # Second teacher
        {'teacher_name': 'Mme Nguveha Cecil', 'class_name': 'Class 1', 'section_type': 'english'},
        
        # Bilingual/French Section Teachers
        {'teacher_name': 'Mme Labo Longpa Josiane', 'class_name': 'SIL', 'section_type': 'bilingual'},
        {'teacher_name': 'Mme Labo Longpa Josiane', 'class_name': 'CP', 'section_type': 'bilingual'},
        {'teacher_name': 'Mme Mbachang Melanie', 'class_name': 'CP', 'section_type': 'bilingual'},
        {'teacher_name': 'Mme Ngakwe Naomi', 'class_name': 'CE1', 'section_type': 'french'},
        {'teacher_name': 'Mme Dongmo Evine', 'class_name': 'CE2', 'section_type': 'french'},
        {'teacher_name': 'Mme Nkwain Prisca', 'class_name': 'CM1', 'section_type': 'french'},
        {'teacher_name': 'Mme Leudjeu Liliane', 'class_name': 'CM2', 'section_type': 'french'},
        
        # Nursery Teachers
        {'teacher_name': 'Mme Fongang Noella', 'class_name': 'Pre-Nursery', 'section_type': 'english'},
        {'teacher_name': 'Mme Epie Zita', 'class_name': 'Nursery 1', 'section_type': 'english'},
        {'teacher_name': 'Mme Fossem Alice', 'class_name': 'Nursery 2', 'section_type': 'english'},
        {'teacher_name': 'Mme Nkayengam Aminatou', 'class_name': 'Moyenne Section', 'section_type': 'bilingual'},
        {'teacher_name': 'Mme Charlotte Mouil', 'class_name': 'Grande Section', 'section_type': 'bilingual'},
    ]
    
    success = 0
    for i, assignment in enumerate(assignments, 1):
        print(f"\n{i}. 📝 {assignment['teacher_name']} → {assignment['class_name']}")
        if assign_teacher(
            teacher_name=assignment['teacher_name'],
            class_name=assignment['class_name'],
            section_type=assignment['section_type']
        ):
            success += 1
    
    print("\n" + "=" * 60)
    print(f"✅ SUMMARY: {success}/{len(assignments)} assignments successful")
    print("=" * 60)

if __name__ == "__main__":
    main()