from django.core.management.base import BaseCommand
from colleges.models import College, ProgramsSection, Program
from courses.models import Course

class Command(BaseCommand):
    help = 'Update the Programs section for Roorkee College of Business Studies'

    def handle(self, *args, **options):
        try:
            # Get the Business Studies college
            college = College.objects.get(name__icontains="Business Studies")
            
            # Get or create the Programs section
            programs_section, created = ProgramsSection.objects.get_or_create(
                college=college,
                defaults={
                    'title': 'Programs Offered',
                    'description': 'Comprehensive business and management education programs designed for modern industry needs. Our diverse range of undergraduate and postgraduate programs in business, commerce, and management are crafted to develop industry-ready professionals with strong analytical, leadership, and entrepreneurial skills.',
                    'has_doctoral_programs': False
                }
            )
            
            # Clear existing programs
            programs_section.programs.all().delete()
            
            # Get all Business Studies courses by their titles
            business_course_titles = [
                'B.Com', 'BBA', 'Bachelors in Hotel Management', 'Bachelors in Hospital Administration',
                'BA English', 'BA Economics', 'BA Tourism & Management', 'MBA Global',
                'MBA in Pharma Management', 'MBA Executive', 'MBA (with IIM Certification) (Finance/HR/Marketing)'
            ]
            business_courses = Course.objects.filter(title__in=business_course_titles)
            
            # Define program data for Business Studies
            programs_data = []
            order_ug = 1
            order_pg = 1
            
            for course in business_courses:
                course_name = course.title
                course_slug = course.slug
                
                # Determine program type and create program data
                if (course_name.startswith('B.') or course_name.startswith('BA ') or 
                    course_name.startswith('Bachelor') or course_name == 'BBA'):
                    programs_data.append({
                        'name': course_name,
                        'link': f'/courses/{course_slug}/',
                        'type': 'UG',
                        'order': order_ug
                    })
                    order_ug += 1
                elif course_name.startswith('MBA') or course_name.startswith('M.'):
                    programs_data.append({
                        'name': course_name,
                        'link': f'/courses/{course_slug}/',
                        'type': 'PG',
                        'order': order_pg
                    })
                    order_pg += 1
            
            # Create programs
            created_count = 0
            for program_data in programs_data:
                program = Program.objects.create(
                    programs_section=programs_section,
                    name=program_data['name'],
                    link=program_data['link'],
                    program_type=program_data['type'],
                    order=program_data['order']
                )
                created_count += 1
                self.stdout.write(f"Created program: {program.name} ({program.get_program_type_display()})")
            
            self.stdout.write(
                self.style.SUCCESS(f'Successfully updated {college.name} with {created_count} programs!')
            )
            
            # Display summary
            self.stdout.write("\n" + "="*50)
            self.stdout.write(self.style.SUCCESS("PROGRAMS SUMMARY:"))
            self.stdout.write("="*50)
            
            ug_programs = programs_section.programs.filter(program_type='UG').count()
            pg_programs = programs_section.programs.filter(program_type='PG').count()
            
            self.stdout.write(f"Undergraduate Programs: {ug_programs}")
            self.stdout.write(f"Postgraduate Programs: {pg_programs}")
            self.stdout.write(f"Total Programs: {created_count}")
            
        except College.DoesNotExist:
            self.stdout.write(
                self.style.ERROR('Business Studies college not found')
            )
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'Error updating programs: {str(e)}')
            )
