import os
from django.core.management.base import BaseCommand
from django.core.files.base import ContentFile
from django.utils.text import slugify
import requests
from io import BytesIO
from django.conf import settings

from courses.models import (
    Course, CourseEligibility, CourseFee, FeeDetail, HostelFee,
    Semester, Subject, CareerProspect, AdmissionStep, DirectAdmission,
    Recruiter, WhyJoin, CourseHighlight, CourseImage, Testimonial
)
from colleges.models import College

class Command(BaseCommand):
    help = 'Seeds the database with courses for Roorkee College of Agricultural Sciences'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to seed Agricultural Sciences courses'))
        
        # Get the Agricultural Sciences college
        try:
            agriculture_college = College.objects.get(slug='roorkee-college-of-agriculture-sciences')
            self.stdout.write(self.style.SUCCESS(f'Found college: {agriculture_college.name}'))
        except College.DoesNotExist:
            self.stdout.write(self.style.ERROR('Agricultural Sciences college not found. Please ensure the college exists.'))
            return
        
        # Create media directories if they don't exist
        os.makedirs(os.path.join(settings.MEDIA_ROOT, 'courses/banners'), exist_ok=True)
        
        # Function to download and save image
        def save_image_from_url(url, field_name):
            try:
                response = requests.get(url)
                if response.status_code == 200:
                    filename = f"{field_name}.jpg"
                    image_content = ContentFile(response.content, name=filename)
                    return image_content
                else:
                    self.stdout.write(self.style.WARNING(f"Failed to download image from {url}"))
                    return None
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"Error downloading image: {str(e)}"))
                return None
        
        # Course data based on raw-data.txt for agricultural sciences
        courses_data = [
            # Undergraduate Programs
            {
                'title': 'B.Sc. Agriculture Hons.',
                'short_description': 'Comprehensive undergraduate program in agricultural sciences with honors, covering crop production, soil science, and sustainable farming practices.',
                'overview': 'The B.Sc. Agriculture Honours program is designed to provide comprehensive knowledge and practical skills in agricultural sciences. Students will learn about crop production, soil management, plant breeding, agricultural economics, and sustainable farming practices. The program combines theoretical knowledge with extensive field work, laboratory sessions, and practical training at agricultural farms. Graduates will be equipped to address modern agricultural challenges and contribute to food security and sustainable development.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Agricultural Sciences'
            },
            {
                'title': 'M.Sc. Agriculture (with Agronomy)',
                'short_description': 'Advanced postgraduate program specializing in agronomy, focusing on crop science, soil management, and agricultural production systems.',
                'overview': 'The M.Sc. Agriculture with Agronomy specialization is an advanced postgraduate program that focuses on the science and practice of crop production and soil management. Students will study advanced topics in crop physiology, soil fertility, weed management, precision agriculture, and sustainable farming systems. The program includes extensive research work, field experiments, and thesis preparation. Graduates will be prepared for leadership roles in agricultural research, extension services, and agribusiness management.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Agricultural Sciences - Agronomy'
            },
            {
                'title': 'M.Sc. Agriculture (with Horticulture)',
                'short_description': 'Specialized postgraduate program in horticulture, covering fruit and vegetable production, ornamental plants, and horticultural technology.',
                'overview': 'The M.Sc. Agriculture with Horticulture specialization provides advanced knowledge in the cultivation of fruits, vegetables, flowers, and ornamental plants. Students will learn about plant breeding, post-harvest technology, greenhouse management, landscape design, and commercial horticulture. The program emphasizes practical training in modern horticultural techniques, biotechnology applications, and sustainable production methods. Graduates will be equipped for careers in horticultural research, commercial production, and agricultural entrepreneurship.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Agricultural Sciences - Horticulture'
            },
            {
                'title': 'M.Sc. Agriculture (with Plant Pathology)',
                'short_description': 'Advanced program focusing on plant diseases, their diagnosis, management, and prevention in agricultural and horticultural crops.',
                'overview': 'The M.Sc. Agriculture with Plant Pathology specialization is designed to train students in the identification, diagnosis, and management of plant diseases. The program covers fungal, bacterial, viral, and nematode diseases affecting crops, as well as integrated pest management strategies. Students will gain expertise in disease surveillance, diagnostic techniques, biological control methods, and the development of disease-resistant varieties. The curriculum includes extensive laboratory work, field studies, and research projects focused on sustainable disease management practices.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Agricultural Sciences - Plant Pathology'
            },
            {
                'title': 'B.Sc. Food Technology',
                'short_description': 'Undergraduate program in food science and technology, covering food processing, preservation, quality control, and food safety.',
                'overview': 'The B.Sc. Food Technology program provides comprehensive training in food science, processing, and technology. Students will learn about food chemistry, microbiology, nutrition, processing techniques, packaging, and quality assurance. The curriculum covers food preservation methods, product development, food safety regulations, and industrial food production. Practical training includes laboratory work, pilot plant operations, and internships in food industries. Graduates will be prepared for careers in food processing companies, quality control laboratories, research institutions, and food service industries.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Food Technology'
            },
            {
                'title': 'B.Sc. Nutrition & Dietetics',
                'short_description': 'Undergraduate program focusing on human nutrition, dietetics, and nutritional health, preparing students for careers in healthcare and nutrition counseling.',
                'overview': 'The B.Sc. Nutrition & Dietetics program is designed to provide comprehensive knowledge of human nutrition, food science, and dietetic practice. Students will study biochemistry, physiology, food composition, nutritional assessment, and therapeutic nutrition. The program covers topics such as community nutrition, sports nutrition, clinical dietetics, and nutrition education. Practical training includes clinical rotations, community health programs, and nutrition counseling sessions. Graduates will be qualified to work as nutritionists, dietitians, health educators, and nutrition consultants in hospitals, healthcare centers, sports facilities, and wellness programs.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Nutrition & Dietetics'
            }
        ]
        
        # Create courses
        for course_data in courses_data:
            # Generate slug
            slug = slugify(course_data['title'])
            
            # Download banner image (using different themes for variety)
            banner_themes = [
                'agriculture,farming,crops', 'food,technology,processing', 
                'nutrition,health,diet', 'plants,science,research',
                'soil,farming,organic', 'laboratory,science,research'
            ]
            theme = banner_themes[hash(course_data['title']) % len(banner_themes)]
            banner_url = f'https://source.unsplash.com/1200x600/?{theme}'
            banner_image = save_image_from_url(banner_url, f'banner_{slug}')
            
            # Create or update course
            course, created = Course.objects.update_or_create(
                slug=slug,
                defaults={
                    'title': course_data['title'],
                    'short_description': course_data['short_description'],
                    'overview': course_data['overview'],
                    'duration': course_data['duration'],
                    'category': course_data['category'],
                }
            )
            
            if banner_image:
                course.banner_image = banner_image
                course.save()
            
            if created:
                self.stdout.write(self.style.SUCCESS(f"Created course: {course.title}"))
            else:
                self.stdout.write(self.style.SUCCESS(f"Updated course: {course.title}"))
            
            # Create basic eligibility for each course
            self._create_course_eligibility(course, course_data)
            
            # Create basic fee structure
            self._create_course_fees(course, course_data)
            
            # Create hostel fee structure
            self._create_hostel_fees(course)
            
            # Create basic highlights
            self._create_course_highlights(course, course_data)
    
    def _create_course_eligibility(self, course, course_data):
        """Create eligibility criteria for the course"""
        if 'M.Sc.' in course.title:
            academic_qual = "Bachelor's degree in Agriculture, Life Sciences, or related field from a recognized university."
            minimum_marks = "Minimum 60% aggregate in graduation (55% for SC/ST/OBC)."
            entrance_exam = "University entrance test or national level examination with personal interview."
        elif 'B.Sc.' in course.title:
            if 'Agriculture' in course.title:
                academic_qual = "10+2 (Senior Secondary) with Physics, Chemistry, Biology/Mathematics from a recognized board."
                minimum_marks = "Minimum 50% aggregate in 10+2 with PCM/PCB (45% for SC/ST/OBC)."
                entrance_exam = "ICAR AIEEA (UG) or University entrance test."
            elif 'Food Technology' in course.title:
                academic_qual = "10+2 (Senior Secondary) with Physics, Chemistry, Mathematics/Biology from a recognized board."
                minimum_marks = "Minimum 50% aggregate in 10+2 with PCM/PCB (45% for SC/ST/OBC)."
                entrance_exam = "JEE Main or University entrance test."
            else:  # Nutrition & Dietetics
                academic_qual = "10+2 (Senior Secondary) with Physics, Chemistry, Biology from a recognized board."
                minimum_marks = "Minimum 50% aggregate in 10+2 with PCB (45% for SC/ST/OBC)."
                entrance_exam = "NEET or University entrance test."
        else:
            academic_qual = "10+2 (Senior Secondary) from a recognized board."
            minimum_marks = "Minimum 50% aggregate in 10+2 (45% for SC/ST/OBC)."
            entrance_exam = "Merit-based admission or entrance examination."
        
        CourseEligibility.objects.update_or_create(
            course=course,
            defaults={
                'academic_qualification': academic_qual,
                'minimum_marks': minimum_marks,
                'entrance_exam': entrance_exam
            }
        )
    
    def _create_course_fees(self, course, course_data):
        """Create fee structure for the course"""
        # Base fees based on course type
        if 'M.Sc.' in course.title:
            domestic_fee = "₹1,80,000 per year"
            international_fee = "$6,000 per year"
        elif 'B.Sc. Agriculture' in course.title:
            domestic_fee = "₹1,50,000 per year"
            international_fee = "$5,500 per year"
        elif 'Food Technology' in course.title:
            domestic_fee = "₹1,40,000 per year"
            international_fee = "$5,000 per year"
        else:  # Nutrition & Dietetics
            domestic_fee = "₹1,20,000 per year"
            international_fee = "$4,500 per year"
        
        CourseFee.objects.update_or_create(
            course=course,
            defaults={
                'domestic': domestic_fee,
                'international': international_fee
            }
        )
    
    def _create_hostel_fees(self, course):
        """Create hostel fee structure for the course"""
        # Hostel fee structure as specified
        HostelFee.objects.update_or_create(
            course=course,
            defaults={
                'fee_per_year': '₹80,000',
                'ac_room_additional': '₹20,000',
                'security_deposit': '₹15,000',
                'notes': 'Hostel fees include accommodation, meals, laundry, and basic amenities. AC rooms are available with additional charges. Security deposit is refundable at the time of leaving the hostel.'
            }
        )
    
    def _create_course_highlights(self, course, course_data):
        """Create course highlights"""
        highlights_data = []
        
        if 'Agriculture' in course.title:
            highlights_data = [
                {'title': 'Practical Farm Training', 'description': 'Extensive hands-on experience in agricultural farms and research stations.', 'icon': 'seedling'},
                {'title': 'Research Opportunities', 'description': 'Opportunities to participate in cutting-edge agricultural research projects.', 'icon': 'microscope'},
                {'title': 'Industry Partnerships', 'description': 'Strong connections with agricultural industries and government agencies.', 'icon': 'handshake'},
                {'title': 'Modern Technology', 'description': 'Training in precision agriculture and modern farming technologies.', 'icon': 'cogs'}
            ]
        elif 'Food Technology' in course.title:
            highlights_data = [
                {'title': 'Pilot Plant Training', 'description': 'Hands-on experience in food processing pilot plants and laboratories.', 'icon': 'industry'},
                {'title': 'Quality Assurance', 'description': 'Comprehensive training in food quality control and safety standards.', 'icon': 'check-circle'},
                {'title': 'Industry Exposure', 'description': 'Internships and training programs with leading food processing companies.', 'icon': 'building'},
                {'title': 'Product Development', 'description': 'Practical experience in new food product development and innovation.', 'icon': 'lightbulb'}
            ]
        elif 'Nutrition' in course.title:
            highlights_data = [
                {'title': 'Clinical Training', 'description': 'Practical training in hospitals and healthcare facilities.', 'icon': 'hospital'},
                {'title': 'Community Programs', 'description': 'Involvement in community nutrition and health promotion programs.', 'icon': 'users'},
                {'title': 'Nutritional Assessment', 'description': 'Training in modern nutritional assessment techniques and tools.', 'icon': 'chart-line'},
                {'title': 'Diet Planning', 'description': 'Expertise in therapeutic diet planning and nutrition counseling.', 'icon': 'apple-alt'}
            ]
        else:
            highlights_data = [
                {'title': 'Expert Faculty', 'description': 'Learn from experienced faculty with industry and research background.', 'icon': 'user-graduate'},
                {'title': 'Modern Facilities', 'description': 'State-of-the-art laboratories and research facilities.', 'icon': 'flask'},
                {'title': 'Research Focus', 'description': 'Strong emphasis on research and innovation in specialized areas.', 'icon': 'search'},
                {'title': 'Career Support', 'description': 'Comprehensive career guidance and placement assistance.', 'icon': 'briefcase'}
            ]
        
        for highlight_data in highlights_data:
            CourseHighlight.objects.update_or_create(
                course=course,
                title=highlight_data['title'],
                defaults={
                    'description': highlight_data['description'],
                    'icon': highlight_data['icon']
                }
            )
        
        self.stdout.write(self.style.SUCCESS('Successfully seeded all Agricultural Sciences courses!'))
