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

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to seed Allied Sciences courses'))
        
        # Get the Allied Sciences college
        try:
            allied_college = College.objects.get(id=5)
            self.stdout.write(self.style.SUCCESS(f'Found college: {allied_college.name} (ID: {allied_college.id})'))
        except College.DoesNotExist:
            self.stdout.write(self.style.ERROR('Allied Sciences college with ID 5 not found.'))
            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 allied sciences
        courses_data = [
            # Undergraduate Programs
            {
                'title': 'B.Pharm',
                'short_description': 'Bachelor of Pharmacy program focusing on pharmaceutical sciences, drug development, and clinical pharmacy practice.',
                'overview': 'The Bachelor of Pharmacy (B.Pharm) is a comprehensive undergraduate program designed to provide students with extensive knowledge in pharmaceutical sciences. The curriculum covers pharmacology, pharmaceutical chemistry, pharmacognosy, pharmaceutics, and clinical pharmacy. Students will learn about drug development, manufacturing processes, quality control, and patient care. The program includes practical training in laboratories, hospitals, and pharmaceutical industries. Graduates will be equipped to work as pharmacists, pharmaceutical researchers, drug regulatory affairs specialists, and healthcare professionals.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Pharmaceutical Sciences'
            },
            {
                'title': 'B.Pharm LE',
                'short_description': 'Bachelor of Pharmacy Lateral Entry program for diploma holders, focusing on advanced pharmaceutical sciences and practice.',
                'overview': 'The Bachelor of Pharmacy Lateral Entry (B.Pharm LE) program is designed for diploma holders in pharmacy who wish to advance their qualifications. This program allows students to directly enter the second year of the B.Pharm curriculum. The course covers advanced pharmaceutical sciences, including clinical pharmacy, hospital pharmacy, community pharmacy, and pharmaceutical marketing. Students will gain expertise in drug interactions, patient counseling, pharmaceutical care, and regulatory affairs. The program prepares graduates for leadership roles in the pharmaceutical industry and healthcare sector.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Pharmaceutical Sciences'
            },
            {
                'title': 'B.Sc. Nursing',
                'short_description': 'Bachelor of Science in Nursing program preparing compassionate healthcare professionals for patient care and nursing practice.',
                'overview': 'The Bachelor of Science in Nursing (B.Sc. Nursing) is a comprehensive program that prepares students to become skilled and compassionate nursing professionals. The curriculum covers anatomy, physiology, pathology, pharmacology, nursing fundamentals, medical-surgical nursing, pediatric nursing, psychiatric nursing, and community health nursing. Students will gain hands-on experience through clinical rotations in hospitals, healthcare centers, and community settings. The program emphasizes evidence-based practice, patient safety, and holistic care. Graduates will be qualified to work as registered nurses in hospitals, clinics, and healthcare institutions.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Nursing Sciences'
            },
            {
                'title': 'B.Sc. Microbiology',
                'short_description': 'Bachelor of Science in Microbiology program exploring microorganisms, their applications, and role in health and disease.',
                'overview': 'The Bachelor of Science in Microbiology program provides comprehensive knowledge about microorganisms and their applications in various fields. Students will study bacteriology, virology, mycology, parasitology, immunology, and biotechnology. The curriculum covers microbial genetics, environmental microbiology, industrial microbiology, and clinical microbiology. Laboratory work includes isolation, identification, and characterization of microorganisms. Students will learn about the role of microbes in health, disease, food production, and environmental processes. Graduates will be prepared for careers in healthcare, biotechnology, pharmaceuticals, food industry, and research institutions.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Life Sciences'
            },
            {
                'title': 'D.Pharm',
                'short_description': 'Diploma in Pharmacy program providing foundational knowledge in pharmaceutical sciences and pharmacy practice.',
                'overview': 'The Diploma in Pharmacy (D.Pharm) is a foundational program that provides essential knowledge and skills in pharmaceutical sciences. The curriculum covers pharmaceutics, pharmaceutical chemistry, pharmacognosy, pharmacology, and hospital pharmacy. Students will learn about drug formulation, quality control, dispensing practices, and patient counseling. The program includes practical training in community pharmacies and hospitals. Graduates will be qualified to work as registered pharmacists, assist in drug dispensing, maintain pharmacy records, and provide basic healthcare services. This program serves as a stepping stone for further education in pharmacy.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Pharmaceutical Sciences'
            },
            # Postgraduate Programs
            {
                'title': 'M.Pharm Pharmaceutics',
                'short_description': 'Master of Pharmacy in Pharmaceutics specializing in drug formulation, delivery systems, and pharmaceutical technology.',
                'overview': 'The Master of Pharmacy in Pharmaceutics is an advanced program focusing on the science and technology of drug formulation and delivery. Students will study advanced pharmaceutics, biopharmaceutics, pharmacokinetics, novel drug delivery systems, and pharmaceutical biotechnology. The curriculum covers tablet technology, capsule formulation, liquid dosage forms, parenteral preparations, and nanotechnology applications. Research work includes developing new formulations, optimizing drug delivery systems, and conducting stability studies. Graduates will be prepared for careers in pharmaceutical research and development, regulatory affairs, and academic institutions.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Pharmaceutical Sciences - Pharmaceutics'
            },
            {
                'title': 'M.Sc. Pharmaceutical Chemistry',
                'short_description': 'Master of Science in Pharmaceutical Chemistry focusing on drug design, synthesis, and medicinal chemistry.',
                'overview': 'The Master of Science in Pharmaceutical Chemistry program provides advanced knowledge in medicinal chemistry and drug design. Students will study organic chemistry, drug metabolism, structure-activity relationships, computer-aided drug design, and analytical techniques. The curriculum covers synthetic organic chemistry, natural product chemistry, and pharmaceutical analysis. Research projects involve drug synthesis, characterization of pharmaceutical compounds, and development of analytical methods. Students will gain expertise in spectroscopic techniques, chromatography, and quality control methods. Graduates will be prepared for careers in pharmaceutical research, drug development, and analytical laboratories.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Pharmaceutical Sciences - Chemistry'
            },
            {
                'title': 'M.Sc. Microbiology',
                'short_description': 'Master of Science in Microbiology program advancing knowledge in microbial sciences, biotechnology, and research applications.',
                'overview': 'The Master of Science in Microbiology is an advanced program that builds upon foundational microbiology knowledge. Students will study advanced bacteriology, virology, immunology, microbial genetics, and biotechnology applications. The curriculum covers molecular microbiology, microbial biotechnology, environmental microbiology, and clinical microbiology. Research work includes studying microbial pathogenesis, developing biotechnological applications, and environmental microbiology studies. Students will gain expertise in advanced laboratory techniques, molecular biology methods, and research methodology. Graduates will be prepared for careers in research institutions, biotechnology companies, pharmaceutical industries, and academic positions.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Life Sciences - Microbiology'
            }
        ]
        
        # 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 = [
                'pharmacy,medicine,pills', 'nursing,healthcare,hospital', 
                'microbiology,laboratory,science', 'pharmaceutical,research,lab',
                'medical,science,research', 'healthcare,medicine,professional'
            ]
            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.Pharm' in course.title or 'M.Sc.' in course.title:
            if 'Pharm' in course.title:
                academic_qual = "Bachelor's degree in Pharmacy (B.Pharm) from a recognized university."
                minimum_marks = "Minimum 55% aggregate in B.Pharm (50% for SC/ST/OBC)."
                entrance_exam = "GPAT (Graduate Pharmacy Aptitude Test) or University entrance test."
            else:  # M.Sc. programs
                academic_qual = "Bachelor's degree in Life Sciences, Microbiology, or related field from a recognized university."
                minimum_marks = "Minimum 55% aggregate in graduation (50% for SC/ST/OBC)."
                entrance_exam = "University entrance test or national level examination."
        elif 'B.Pharm' in course.title:
            if 'LE' in course.title:
                academic_qual = "Diploma in Pharmacy (D.Pharm) from a recognized institution."
                minimum_marks = "Minimum 50% aggregate in D.Pharm (45% for SC/ST/OBC)."
                entrance_exam = "University entrance test or merit-based admission."
            else:
                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 = "JEE Main or University entrance test."
        elif 'B.Sc. Nursing' in course.title:
            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."
        elif 'B.Sc.' in course.title:
            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 = "University entrance test or merit-based admission."
        elif 'D.Pharm' 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 = "University entrance test or merit-based admission."
        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.Pharm' in course.title or 'M.Sc.' in course.title:
            domestic_fee = "₹2,00,000 per year"
            international_fee = "$7,000 per year"
        elif 'B.Pharm' in course.title:
            if 'LE' in course.title:
                domestic_fee = "₹1,60,000 per year"
                international_fee = "$5,800 per year"
            else:
                domestic_fee = "₹1,70,000 per year"
                international_fee = "$6,200 per year"
        elif 'B.Sc. Nursing' in course.title:
            domestic_fee = "₹1,80,000 per year"
            international_fee = "$6,500 per year"
        elif 'B.Sc.' in course.title:
            domestic_fee = "₹1,30,000 per year"
            international_fee = "$4,800 per year"
        elif 'D.Pharm' in course.title:
            domestic_fee = "₹1,10,000 per year"
            international_fee = "$4,000 per year"
        else:
            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 'Pharm' in course.title:
            highlights_data = [
                {'title': 'Modern Laboratories', 'description': 'State-of-the-art pharmaceutical laboratories with latest equipment and instruments.', 'icon': 'flask'},
                {'title': 'Industry Training', 'description': 'Internships and training programs with leading pharmaceutical companies.', 'icon': 'industry'},
                {'title': 'Clinical Exposure', 'description': 'Practical training in hospitals and community pharmacies for real-world experience.', 'icon': 'hospital'},
                {'title': 'Research Opportunities', 'description': 'Opportunities to participate in pharmaceutical research and drug development projects.', 'icon': 'microscope'}
            ]
        elif 'Nursing' in course.title:
            highlights_data = [
                {'title': 'Clinical Training', 'description': 'Extensive clinical rotations in multi-specialty hospitals and healthcare centers.', 'icon': 'user-md'},
                {'title': 'Simulation Labs', 'description': 'Advanced nursing simulation laboratories for skill development and practice.', 'icon': 'heartbeat'},
                {'title': 'Community Health', 'description': 'Hands-on experience in community health programs and rural healthcare.', 'icon': 'users'},
                {'title': 'Professional Development', 'description': 'Comprehensive training in nursing ethics, leadership, and patient care.', 'icon': 'graduation-cap'}
            ]
        elif 'Microbiology' in course.title:
            highlights_data = [
                {'title': 'Advanced Laboratories', 'description': 'Well-equipped microbiology labs with modern instruments and safety facilities.', 'icon': 'microscope'},
                {'title': 'Research Projects', 'description': 'Opportunities to work on cutting-edge research in microbiology and biotechnology.', 'icon': 'search'},
                {'title': 'Industry Connections', 'description': 'Strong partnerships with biotechnology and pharmaceutical companies.', 'icon': 'handshake'},
                {'title': 'Field Studies', 'description': 'Practical exposure through field studies and environmental microbiology projects.', 'icon': 'leaf'}
            ]
        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': 'Practical Training', 'description': 'Extensive hands-on training and practical exposure.', 'icon': 'cogs'},
                {'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 Allied Sciences courses!'))
