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 Agriculture Sciences'

    def handle(self, *args, **options):
        try:
            # Get the Agriculture Sciences college
            college = College.objects.get(slug='roorkee-college-of-agriculture-sciences')
            
            # Get or create the Programs section
            programs_section, created = ProgramsSection.objects.get_or_create(
                college=college,
                defaults={
                    'title': 'Programs Offered',
                    'description': 'Comprehensive agricultural sciences and food technology programs designed to address modern agricultural challenges and sustainable development. Our diverse range of undergraduate and postgraduate programs prepare students for careers in agriculture, food technology, nutrition, and related fields.',
                    'has_doctoral_programs': False
                }
            )
            
            # Clear existing programs
            programs_section.programs.all().delete()
            
            # Get all Agriculture Sciences courses by their titles
            agriculture_course_titles = [
                'B.Sc. Agriculture Hons.', 'M.Sc. Agriculture (with Agronomy)', 
                'M.Sc. Agriculture (with Horticulture)', 'M.Sc. Agriculture (with Plant Pathology)',
                'B.Sc. Food Technology', 'B.Sc. Nutrition & Dietetics'
            ]
            agriculture_courses = Course.objects.filter(title__in=agriculture_course_titles)
            
            # Define program data for Agriculture Sciences
            programs_data = []
            order_ug = 1
            order_pg = 1
            
            for course in agriculture_courses:
                course_name = course.title
                course_slug = course.slug
                
                # Determine program type and create program data
                if (course_name.startswith('B.Sc.') or course_name.startswith('B.')):
                    programs_data.append({
                        'name': course_name,
                        'link': f'/academics/programs/courses/{course_slug}/',
                        'type': 'UG',
                        'order': order_ug
                    })
                    order_ug += 1
                elif course_name.startswith('M.Sc.') or course_name.startswith('M.'):
                    programs_data.append({
                        'name': course_name,
                        'link': f'/academics/programs/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('Agriculture Sciences college not found')
            )
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'Error updating programs: {str(e)}')
            )
