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
)

class Command(BaseCommand):
    help = 'Creates comprehensive content for all Engineering courses'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to create content for Engineering courses'))
        
        # Get engineering courses (exclude Smart Computing courses)
        engineering_courses = Course.objects.filter(
            category__in=[
                'Civil Engineering', 
                'Electronics & Communication Engineering',
                'Electrical & Electronics Engineering', 
                'Mechanical Engineering'
            ]
        ).order_by('id')
        
        for course in engineering_courses:
            self.stdout.write(f"\n--- Creating content for: {course.title} ---")
            
            # Create semesters and subjects
            self._create_semesters_and_subjects(course)
            
            # Create career prospects
            self._create_career_prospects(course)
            
            # Create admission steps
            self._create_admission_steps(course)
            
            # Create direct admission info
            self._create_direct_admission(course)
            
            # Create fee details
            self._create_fee_details(course)
            
            # Create hostel fee
            self._create_hostel_fee(course)
            
            # Create recruiters
            self._create_recruiters(course)
            
            # Create why join reasons
            self._create_why_join(course)
            
            # Create testimonials
            self._create_testimonials(course)
            
            self.stdout.write(self.style.SUCCESS(f"✓ Completed content for {course.title}"))
        
        self.stdout.write(self.style.SUCCESS('\n🎉 Successfully created content for all Engineering courses!'))

    def _create_semesters_and_subjects(self, course):
        """Create semesters and subjects based on course type"""
        # Determine number of semesters based on duration
        if '4 Years' in course.duration:
            num_semesters = 8
        elif '3 Years' in course.duration:
            num_semesters = 6
        elif '2 Years' in course.duration:
            num_semesters = 4
        elif 'Ph.D' in course.title:
            num_semesters = 6  # Ph.D. coursework semesters
        else:
            num_semesters = 6  # Default
        
        # Create semesters
        for sem_num in range(1, num_semesters + 1):
            semester, created = Semester.objects.get_or_create(
                course=course,
                number=sem_num,
                defaults={'name': f'Semester {sem_num}'}
            )
            
            # Create subjects for each semester
            subjects = self._get_subjects_for_semester(course, sem_num)
            for subject_data in subjects:
                Subject.objects.get_or_create(
                    semester=semester,
                    code=subject_data['code'],
                    defaults={
                        'name': subject_data['name'],
                        'credits': subject_data['credits'],
                        'description': subject_data['description']
                    }
                )
    
    def _get_subjects_for_semester(self, course, semester_num):
        """Get subjects based on course type and semester"""
        # Common foundation subjects for all engineering courses
        foundation_subjects = {
            1: [
                {'code': 'MA101', 'name': 'Engineering Mathematics I', 'credits': 4, 'description': 'Calculus, differential equations, linear algebra, and matrices.'},
                {'code': 'PH101', 'name': 'Engineering Physics', 'credits': 3, 'description': 'Mechanics, thermodynamics, waves, optics, and modern physics.'},
                {'code': 'CH101', 'name': 'Engineering Chemistry', 'credits': 3, 'description': 'Atomic structure, chemical bonding, thermodynamics, and materials.'},
                {'code': 'HU101', 'name': 'Communication Skills', 'credits': 2, 'description': 'English proficiency, technical writing, and presentation skills.'},
                {'code': 'ME101', 'name': 'Engineering Graphics', 'credits': 3, 'description': 'Technical drawing, orthographic projections, and CAD fundamentals.'},
            ],
            2: [
                {'code': 'MA102', 'name': 'Engineering Mathematics II', 'credits': 4, 'description': 'Advanced calculus, vector calculus, and partial differential equations.'},
                {'code': 'PH102', 'name': 'Applied Physics', 'credits': 3, 'description': 'Electromagnetic theory, quantum mechanics, and semiconductor physics.'},
                {'code': 'CS101', 'name': 'Computer Programming', 'credits': 4, 'description': 'Programming fundamentals using C language and problem solving.'},
                {'code': 'HU102', 'name': 'Professional Ethics', 'credits': 2, 'description': 'Engineering ethics, professional responsibility, and social impact.'},
            ]
        }
        
        # Branch-specific subjects
        if 'Civil' in course.title:
            civil_subjects = {
                3: [
                    {'code': 'CE301', 'name': 'Strength of Materials', 'credits': 4, 'description': 'Stress, strain, bending moment, shear force, and deflection analysis.'},
                    {'code': 'CE302', 'name': 'Fluid Mechanics', 'credits': 4, 'description': 'Fluid properties, hydrostatics, fluid flow, and Bernoulli equation.'},
                    {'code': 'CE303', 'name': 'Building Materials', 'credits': 3, 'description': 'Properties of cement, concrete, steel, and other construction materials.'},
                    {'code': 'CE304', 'name': 'Surveying', 'credits': 4, 'description': 'Principles of surveying, leveling, theodolite, and modern surveying techniques.'},
                ],
                4: [
                    {'code': 'CE401', 'name': 'Structural Analysis', 'credits': 4, 'description': 'Analysis of determinate and indeterminate structures using various methods.'},
                    {'code': 'CE402', 'name': 'Geotechnical Engineering', 'credits': 4, 'description': 'Soil mechanics, foundation engineering, and earth pressure analysis.'},
                    {'code': 'CE403', 'name': 'Concrete Technology', 'credits': 3, 'description': 'Concrete mix design, properties, testing, and quality control.'},
                    {'code': 'CE404', 'name': 'Transportation Engineering', 'credits': 3, 'description': 'Highway engineering, traffic engineering, and transportation planning.'},
                ],
                5: [
                    {'code': 'CE501', 'name': 'Design of Steel Structures', 'credits': 4, 'description': 'Design of steel beams, columns, connections, and steel structures.'},
                    {'code': 'CE502', 'name': 'Design of Concrete Structures', 'credits': 4, 'description': 'RCC design principles, beams, slabs, columns, and footings.'},
                    {'code': 'CE503', 'name': 'Water Resources Engineering', 'credits': 3, 'description': 'Hydrology, irrigation engineering, and water supply systems.'},
                ],
                6: [
                    {'code': 'CE601', 'name': 'Environmental Engineering', 'credits': 4, 'description': 'Water treatment, wastewater treatment, and environmental pollution control.'},
                    {'code': 'CE602', 'name': 'Project Management', 'credits': 3, 'description': 'Construction planning, scheduling, cost estimation, and project control.'},
                    {'code': 'CE603', 'name': 'Earthquake Engineering', 'credits': 3, 'description': 'Seismic analysis, earthquake-resistant design, and structural dynamics.'},
                ]
            }
            foundation_subjects.update(civil_subjects)
        
        elif 'Electronics & Communication' in course.title:
            ece_subjects = {
                3: [
                    {'code': 'EC301', 'name': 'Electronic Devices', 'credits': 4, 'description': 'Semiconductor physics, diodes, transistors, and FET characteristics.'},
                    {'code': 'EC302', 'name': 'Network Analysis', 'credits': 4, 'description': 'Circuit analysis techniques, network theorems, and AC/DC circuits.'},
                    {'code': 'EC303', 'name': 'Digital Electronics', 'credits': 3, 'description': 'Boolean algebra, logic gates, combinational and sequential circuits.'},
                    {'code': 'EC304', 'name': 'Signals and Systems', 'credits': 4, 'description': 'Time and frequency domain analysis, Fourier transforms, and system analysis.'},
                ],
                4: [
                    {'code': 'EC401', 'name': 'Analog Circuits', 'credits': 4, 'description': 'Amplifier design, operational amplifiers, and analog circuit applications.'},
                    {'code': 'EC402', 'name': 'Microprocessors', 'credits': 4, 'description': '8085/8086 microprocessor architecture, programming, and interfacing.'},
                    {'code': 'EC403', 'name': 'Communication Systems', 'credits': 3, 'description': 'Analog and digital communication, modulation techniques, and noise analysis.'},
                    {'code': 'EC404', 'name': 'Control Systems', 'credits': 3, 'description': 'System modeling, stability analysis, and controller design.'},
                ],
                5: [
                    {'code': 'EC501', 'name': 'VLSI Design', 'credits': 4, 'description': 'IC fabrication, digital VLSI design, and layout techniques.'},
                    {'code': 'EC502', 'name': 'Digital Signal Processing', 'credits': 4, 'description': 'Discrete signals, Z-transforms, digital filters, and DSP applications.'},
                    {'code': 'EC503', 'name': 'Embedded Systems', 'credits': 3, 'description': 'Microcontroller programming, real-time systems, and embedded applications.'},
                ],
                6: [
                    {'code': 'EC601', 'name': 'Wireless Communication', 'credits': 4, 'description': 'Mobile communication, cellular systems, and wireless protocols.'},
                    {'code': 'EC602', 'name': 'Optical Communication', 'credits': 3, 'description': 'Fiber optic communication systems and optical networking.'},
                    {'code': 'EC603', 'name': 'Antenna Theory', 'credits': 3, 'description': 'Antenna principles, radiation patterns, and antenna design.'},
                ]
            }
            foundation_subjects.update(ece_subjects)
        
        elif 'Electrical' in course.title:
            eee_subjects = {
                3: [
                    {'code': 'EE301', 'name': 'Electrical Machines I', 'credits': 4, 'description': 'DC machines, transformers, and their performance analysis.'},
                    {'code': 'EE302', 'name': 'Circuit Analysis', 'credits': 4, 'description': 'AC/DC circuit analysis, network theorems, and resonance.'},
                    {'code': 'EE303', 'name': 'Electronic Devices', 'credits': 3, 'description': 'Semiconductor devices, diodes, transistors, and their characteristics.'},
                    {'code': 'EE304', 'name': 'Electrical Measurements', 'credits': 4, 'description': 'Measurement techniques, instruments, and measurement systems.'},
                ],
                4: [
                    {'code': 'EE401', 'name': 'Electrical Machines II', 'credits': 4, 'description': 'Induction machines, synchronous machines, and special machines.'},
                    {'code': 'EE402', 'name': 'Power Electronics', 'credits': 4, 'description': 'Power semiconductor devices, converters, and inverters.'},
                    {'code': 'EE403', 'name': 'Control Systems', 'credits': 3, 'description': 'System modeling, stability analysis, and automatic control.'},
                    {'code': 'EE404', 'name': 'Electromagnetic Fields', 'credits': 3, 'description': 'Maxwell equations, electromagnetic wave propagation, and applications.'},
                ],
                5: [
                    {'code': 'EE501', 'name': 'Power Systems I', 'credits': 4, 'description': 'Power generation, transmission lines, and power system components.'},
                    {'code': 'EE502', 'name': 'Industrial Drives', 'credits': 4, 'description': 'Motor drives, speed control, and industrial automation.'},
                    {'code': 'EE503', 'name': 'Renewable Energy Systems', 'credits': 3, 'description': 'Solar, wind, and other renewable energy technologies.'},
                ],
                6: [
                    {'code': 'EE601', 'name': 'Power Systems II', 'credits': 4, 'description': 'Power system protection, stability, and smart grid technologies.'},
                    {'code': 'EE602', 'name': 'High Voltage Engineering', 'credits': 3, 'description': 'High voltage phenomena, insulation, and testing techniques.'},
                    {'code': 'EE603', 'name': 'Electric Vehicle Technology', 'credits': 3, 'description': 'EV systems, battery technology, and charging infrastructure.'},
                ]
            }
            foundation_subjects.update(eee_subjects)
        
        elif 'Mechanical' in course.title:
            me_subjects = {
                3: [
                    {'code': 'ME301', 'name': 'Thermodynamics', 'credits': 4, 'description': 'Laws of thermodynamics, cycles, and thermodynamic processes.'},
                    {'code': 'ME302', 'name': 'Strength of Materials', 'credits': 4, 'description': 'Stress, strain, bending, torsion, and material failure theories.'},
                    {'code': 'ME303', 'name': 'Fluid Mechanics', 'credits': 3, 'description': 'Fluid properties, flow analysis, and fluid machinery fundamentals.'},
                    {'code': 'ME304', 'name': 'Manufacturing Processes', 'credits': 4, 'description': 'Casting, forming, machining, and modern manufacturing techniques.'},
                ],
                4: [
                    {'code': 'ME401', 'name': 'Heat Transfer', 'credits': 4, 'description': 'Conduction, convection, radiation, and heat exchanger design.'},
                    {'code': 'ME402', 'name': 'Machine Design', 'credits': 4, 'description': 'Design of machine elements, gears, bearings, and mechanical systems.'},
                    {'code': 'ME403', 'name': 'Internal Combustion Engines', 'credits': 3, 'description': 'Engine cycles, combustion, performance, and emission control.'},
                    {'code': 'ME404', 'name': 'Dynamics of Machines', 'credits': 3, 'description': 'Kinematics, dynamics, and vibration analysis of mechanisms.'},
                ],
                5: [
                    {'code': 'ME501', 'name': 'CAD/CAM', 'credits': 4, 'description': 'Computer-aided design, manufacturing, and CNC programming.'},
                    {'code': 'ME502', 'name': 'Refrigeration & Air Conditioning', 'credits': 4, 'description': 'Refrigeration cycles, HVAC systems, and psychrometrics.'},
                    {'code': 'ME503', 'name': 'Industrial Engineering', 'credits': 3, 'description': 'Work study, production planning, and quality control.'},
                ],
                6: [
                    {'code': 'ME601', 'name': 'Automation & Robotics', 'credits': 4, 'description': 'Industrial automation, robotics, and programmable controllers.'},
                    {'code': 'ME602', 'name': 'Finite Element Analysis', 'credits': 3, 'description': 'FEA principles, modeling, and structural analysis software.'},
                    {'code': 'ME603', 'name': 'Automotive Engineering', 'credits': 3, 'description': 'Vehicle systems, chassis design, and automotive technologies.'},
                ]
            }
            foundation_subjects.update(me_subjects)
        
        return foundation_subjects.get(semester_num, [])

    def _create_career_prospects(self, course):
        """Create career prospects based on course type"""
        if 'Civil' in course.title:
            if 'Ph.D' in course.title:
                prospects = [
                    {'title': 'Research Scientist', 'salary_range': '₹8-20 LPA', 'description': 'Conduct advanced research in civil engineering and structural systems.'},
                    {'title': 'Professor/Academic', 'salary_range': '₹6-18 LPA', 'description': 'Teaching and research positions in universities and institutes.'},
                    {'title': 'R&D Engineer', 'salary_range': '₹10-25 LPA', 'description': 'Research and development in construction and infrastructure companies.'},
                    {'title': 'Consulting Engineer', 'salary_range': '₹12-30 LPA', 'description': 'Independent consulting in specialized civil engineering areas.'},
                ]
            else:
                prospects = [
                    {'title': 'Structural Engineer', 'salary_range': '₹4-15 LPA', 'description': 'Design and analysis of buildings, bridges, and other structures.'},
                    {'title': 'Construction Manager', 'salary_range': '₹5-18 LPA', 'description': 'Manage construction projects and coordinate site activities.'},
                    {'title': 'Transportation Engineer', 'salary_range': '₹4-14 LPA', 'description': 'Design highways, traffic systems, and transportation infrastructure.'},
                    {'title': 'Environmental Engineer', 'salary_range': '₹4-16 LPA', 'description': 'Work on water treatment, waste management, and environmental projects.'},
                ]
        elif 'Electronics & Communication' in course.title:
            if 'Ph.D' in course.title:
                prospects = [
                    {'title': 'Research Scientist (Electronics)', 'salary_range': '₹10-25 LPA', 'description': 'Advanced research in VLSI, communication systems, and emerging technologies.'},
                    {'title': 'Professor/Academic', 'salary_range': '₹6-18 LPA', 'description': 'Teaching and research in universities and technical institutes.'},
                    {'title': 'Principal Engineer', 'salary_range': '₹15-35 LPA', 'description': 'Lead technical teams in semiconductor and communication companies.'},
                    {'title': 'Innovation Consultant', 'salary_range': '₹12-30 LPA', 'description': 'Technology consulting and innovation management.'},
                ]
            else:
                prospects = [
                    {'title': 'Electronics Engineer', 'salary_range': '₹4-16 LPA', 'description': 'Design and develop electronic circuits and systems.'},
                    {'title': 'VLSI Design Engineer', 'salary_range': '₹6-20 LPA', 'description': 'Design integrated circuits and semiconductor devices.'},
                    {'title': 'Communication Engineer', 'salary_range': '₹5-18 LPA', 'description': 'Work on wireless communication and networking systems.'},
                    {'title': 'Embedded Systems Engineer', 'salary_range': '₹4-16 LPA', 'description': 'Develop embedded systems for various applications.'},
                ]
        elif 'Electrical' in course.title:
            if 'Ph.D' in course.title:
                prospects = [
                    {'title': 'Power Systems Researcher', 'salary_range': '₹10-24 LPA', 'description': 'Research in smart grids, renewable energy, and power systems.'},
                    {'title': 'Professor/Academic', 'salary_range': '₹6-18 LPA', 'description': 'Academic positions in electrical engineering departments.'},
                    {'title': 'Chief Engineer', 'salary_range': '₹15-35 LPA', 'description': 'Senior technical positions in power and energy companies.'},
                    {'title': 'Energy Consultant', 'salary_range': '₹12-28 LPA', 'description': 'Consulting in renewable energy and power system projects.'},
                ]
            else:
                prospects = [
                    {'title': 'Electrical Engineer', 'salary_range': '₹4-15 LPA', 'description': 'Design and maintain electrical systems and equipment.'},
                    {'title': 'Power Systems Engineer', 'salary_range': '₹5-18 LPA', 'description': 'Work on power generation, transmission, and distribution.'},
                    {'title': 'Control Systems Engineer', 'salary_range': '₹5-17 LPA', 'description': 'Design automated control systems for industries.'},
                    {'title': 'Renewable Energy Engineer', 'salary_range': '₹4-16 LPA', 'description': 'Develop solar, wind, and other renewable energy projects.'},
                ]
        elif 'Mechanical' in course.title:
            if 'Ph.D' in course.title:
                prospects = [
                    {'title': 'Manufacturing Research Scientist', 'salary_range': '₹10-25 LPA', 'description': 'Research in advanced manufacturing and materials.'},
                    {'title': 'Professor/Academic', 'salary_range': '₹6-18 LPA', 'description': 'Teaching and research in mechanical engineering.'},
                    {'title': 'Chief Technology Officer', 'salary_range': '₹20-40 LPA', 'description': 'Technical leadership in automotive and manufacturing companies.'},
                    {'title': 'Innovation Manager', 'salary_range': '₹15-32 LPA', 'description': 'Lead innovation and technology development initiatives.'},
                ]
            else:
                prospects = [
                    {'title': 'Mechanical Engineer', 'salary_range': '₹4-15 LPA', 'description': 'Design and develop mechanical systems and machinery.'},
                    {'title': 'Manufacturing Engineer', 'salary_range': '₹4-16 LPA', 'description': 'Optimize manufacturing processes and production systems.'},
                    {'title': 'Automotive Engineer', 'salary_range': '₹5-18 LPA', 'description': 'Work on vehicle design and automotive technologies.'},
                    {'title': 'Project Engineer', 'salary_range': '₹4-14 LPA', 'description': 'Manage engineering projects and technical implementations.'},
                ]
        else:
            # Default prospects for any unmatched courses
            prospects = [
                {'title': 'Engineer', 'salary_range': '₹4-15 LPA', 'description': 'Work in engineering design, development, and implementation.'},
                {'title': 'Technical Specialist', 'salary_range': '₹5-18 LPA', 'description': 'Provide technical expertise in specialized engineering areas.'},
                {'title': 'Project Coordinator', 'salary_range': '₹4-14 LPA', 'description': 'Coordinate technical projects and engineering activities.'},
                {'title': 'Quality Engineer', 'salary_range': '₹4-16 LPA', 'description': 'Ensure quality standards in engineering processes and products.'},
            ]
        
        for prospect_data in prospects:
            CareerProspect.objects.get_or_create(
                course=course,
                title=prospect_data['title'],
                defaults={
                    'salary_range': prospect_data['salary_range'],
                    'description': prospect_data['description']
                }
            )

    def _create_admission_steps(self, course):
        """Create admission steps for the course"""
        if 'LE' in course.title:  # Lateral Entry
            steps = [
                {'title': 'Eligibility Verification', 'description': 'Ensure completion of diploma in relevant engineering field with required marks.', 'order': 1},
                {'title': 'Application Submission', 'description': 'Submit online application with diploma certificates and transcripts.', 'order': 2},
                {'title': 'Lateral Entry Test', 'description': 'Appear for lateral entry examination covering diploma curriculum.', 'order': 3},
                {'title': 'Merit List & Counseling', 'description': 'Check merit list and participate in counseling for seat allocation.', 'order': 4},
                {'title': 'Document Verification & Admission', 'description': 'Complete document verification and admission formalities with fee payment.', 'order': 5},
            ]
        elif 'Ph.D' in course.title:
            steps = [
                {'title': 'Research Proposal', 'description': 'Prepare and submit research proposal in your area of interest.', 'order': 1},
                {'title': 'Entrance Examination', 'description': 'Qualify university research entrance test or NET/GATE.', 'order': 2},
                {'title': 'Interview & Presentation', 'description': 'Present research proposal and attend interview with faculty panel.', 'order': 3},
                {'title': 'Supervisor Allocation', 'description': 'Get assigned research supervisor based on research area.', 'order': 4},
                {'title': 'Registration & Enrollment', 'description': 'Complete registration formalities and begin research work.', 'order': 5},
            ]
        elif 'M.Tech' in course.title:
            steps = [
                {'title': 'GATE Qualification', 'description': 'Qualify GATE examination or university entrance test.', 'order': 1},
                {'title': 'Application Process', 'description': 'Submit application with GATE scorecard and academic transcripts.', 'order': 2},
                {'title': 'Merit-based Selection', 'description': 'Selection based on GATE score and academic performance.', 'order': 3},
                {'title': 'Document Verification', 'description': 'Verify original documents and certificates.', 'order': 4},
                {'title': 'Admission Confirmation', 'description': 'Pay fees and confirm admission to secure seat.', 'order': 5},
            ]
        elif 'Diploma' in course.title:
            steps = [
                {'title': '10th Marks Verification', 'description': 'Check eligibility based on 10th standard marks and subjects.', 'order': 1},
                {'title': 'Application Form', 'description': 'Fill online application form with personal and academic details.', 'order': 2},
                {'title': 'Merit List', 'description': 'Check merit list based on 10th standard performance.', 'order': 3},
                {'title': 'Counseling Process', 'description': 'Attend counseling for course and specialization selection.', 'order': 4},
                {'title': 'Admission Completion', 'description': 'Complete admission with document verification and fee payment.', 'order': 5},
            ]
        else:  # B.Tech courses
            steps = [
                {'title': 'Eligibility Check', 'description': 'Verify 10+2 completion with PCM subjects and minimum marks.', 'order': 1},
                {'title': 'Entrance Examination', 'description': 'Appear for JEE Main or state entrance examination.', 'order': 2},
                {'title': 'Application Submission', 'description': 'Submit application with entrance exam scores and 10+2 certificates.', 'order': 3},
                {'title': 'Counseling & Seat Allocation', 'description': 'Participate in counseling based on entrance exam rank.', 'order': 4},
                {'title': 'Admission Formalities', 'description': 'Complete document verification, fee payment, and enrollment.', 'order': 5},
            ]
        
        for step_data in steps:
            AdmissionStep.objects.get_or_create(
                course=course,
                title=step_data['title'],
                order=step_data['order'],
                defaults={'description': step_data['description']}
            )

    def _create_direct_admission(self, course):
        """Create direct admission information"""
        if 'Ph.D' in course.title:
            description = "Direct admission available for candidates with UGC-NET/JRF qualification or outstanding academic record. Industry professionals with significant research experience may also be considered for direct admission."
            is_available = True
        elif 'M.Tech' in course.title:
            description = "Direct admission available for GATE qualified candidates with high scores. Sponsored candidates from industry and government organizations are also eligible for direct admission."
            is_available = True
        elif 'Hons' in course.title:
            description = "Direct admission available for meritorious students with exceptional performance in JEE Main or state entrance examinations. Students with 95+ percentile may qualify for direct admission."
            is_available = True
        else:
            description = "Direct admission available based on merit in qualifying examinations. Students meeting minimum cut-off criteria can apply for direct admission without entrance test."
            is_available = True
        
        DirectAdmission.objects.get_or_create(
            course=course,
            defaults={
                'description': description,
                'is_available': is_available
            }
        )

    def _create_fee_details(self, course):
        """Create detailed fee structure"""
        try:
            course_fee = course.fees
            
            # Determine fee structure based on course type
            if 'Ph.D' in course.title:
                fee_details = [
                    {'fee_head': 'Registration Fee', 'first_year': '₹10,000', 'second_year': '₹0', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': True},
                    {'fee_head': 'Course Fee', 'first_year': '₹25,000', 'second_year': '₹25,000', 'third_year': '₹10,000', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Research Fee', 'first_year': '₹15,000', 'second_year': '₹15,000', 'third_year': '₹15,000', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Library Fee', 'first_year': '₹5,000', 'second_year': '₹5,000', 'third_year': '₹5,000', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Thesis Fee', 'first_year': '₹5,000', 'second_year': '₹0', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': True},
                ]
            elif 'M.Tech' in course.title:
                fee_details = [
                    {'fee_head': 'Tuition Fee', 'first_year': '₹1,60,000', 'second_year': '₹1,60,000', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Registration Fee', 'first_year': '₹10,000', 'second_year': '₹0', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': True},
                    {'fee_head': 'Laboratory Fee', 'first_year': '₹20,000', 'second_year': '₹20,000', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Library Fee', 'first_year': '₹5,000', 'second_year': '₹5,000', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Examination Fee', 'first_year': '₹5,000', 'second_year': '₹5,000', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': False},
                ]
            elif 'B.Tech' in course.title:
                fee_details = [
                    {'fee_head': 'Tuition Fee', 'first_year': '₹1,50,000', 'second_year': '₹1,50,000', 'third_year': '₹1,50,000', 'fourth_year': '₹1,50,000', 'is_one_time': False},
                    {'fee_head': 'Registration Fee', 'first_year': '₹10,000', 'second_year': '₹0', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': True},
                    {'fee_head': 'Laboratory Fee', 'first_year': '₹15,000', 'second_year': '₹15,000', 'third_year': '₹20,000', 'fourth_year': '₹20,000', 'is_one_time': False},
                    {'fee_head': 'Library Fee', 'first_year': '₹5,000', 'second_year': '₹5,000', 'third_year': '₹5,000', 'fourth_year': '₹5,000', 'is_one_time': False},
                    {'fee_head': 'Development Fee', 'first_year': '₹10,000', 'second_year': '₹10,000', 'third_year': '₹10,000', 'fourth_year': '₹10,000', 'is_one_time': False},
                    {'fee_head': 'Examination Fee', 'first_year': '₹5,000', 'second_year': '₹5,000', 'third_year': '₹5,000', 'fourth_year': '₹5,000', 'is_one_time': False},
                ]
            else:  # Diploma
                fee_details = [
                    {'fee_head': 'Tuition Fee', 'first_year': '₹65,000', 'second_year': '₹65,000', 'third_year': '₹65,000', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Registration Fee', 'first_year': '₹5,000', 'second_year': '₹0', 'third_year': '₹0', 'fourth_year': '₹0', 'is_one_time': True},
                    {'fee_head': 'Laboratory Fee', 'first_year': '₹10,000', 'second_year': '₹10,000', 'third_year': '₹10,000', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Library Fee', 'first_year': '₹3,000', 'second_year': '₹3,000', 'third_year': '₹3,000', 'fourth_year': '₹0', 'is_one_time': False},
                    {'fee_head': 'Examination Fee', 'first_year': '₹2,000', 'second_year': '₹2,000', 'third_year': '₹2,000', 'fourth_year': '₹0', 'is_one_time': False},
                ]
            
            for fee_data in fee_details:
                FeeDetail.objects.get_or_create(
                    course_fee=course_fee,
                    fee_head=fee_data['fee_head'],
                    defaults={
                        'first_year': fee_data['first_year'],
                        'second_year': fee_data['second_year'],
                        'third_year': fee_data['third_year'],
                        'fourth_year': fee_data['fourth_year'],
                        'is_one_time': fee_data['is_one_time']
                    }
                )
        except Exception as e:
            self.stdout.write(self.style.WARNING(f"Could not create fee details for {course.title}: {str(e)}"))

    def _create_hostel_fee(self, course):
        """Create hostel fee information"""
        HostelFee.objects.get_or_create(
            course=course,
            defaults={
                'fee_per_year': '₹85,000',
                'ac_room_additional': '₹25,000',
                'security_deposit': '₹20,000',
                'notes': 'Hostel fees include accommodation, meals, laundry, and basic utilities. AC rooms available with additional charges. Security deposit is fully refundable upon checkout with no damages.'
            }
        )

    def _create_recruiters(self, course):
        """Create recruiter information"""
        if 'Civil' in course.title:
            recruiters = ['L&T', 'Tata Projects', 'Shapoorji Pallonji', 'Godrej Properties', 'DLF', 'IRCON', 'NHPC', 'Larsen & Toubro', 'Hindustan Construction', 'Reliance Infrastructure']
        elif 'Electronics & Communication' in course.title:
            recruiters = ['Intel', 'Qualcomm', 'Broadcom', 'Samsung', 'TSMC', 'MediaTek', 'Texas Instruments', 'Analog Devices', 'Infineon', 'STMicroelectronics']
        elif 'Electrical' in course.title:
            recruiters = ['Siemens', 'ABB', 'Schneider Electric', 'GE', 'Emerson', 'Honeywell', 'Crompton Greaves', 'BHEL', 'Tata Power', 'Reliance Energy']
        elif 'Mechanical' in course.title:
            recruiters = ['Tata Motors', 'Mahindra', 'Bajaj Auto', 'Hero MotoCorp', 'Maruti Suzuki', 'Hyundai', 'Ford', 'Bosch', 'Cummins', 'Caterpillar']
        else:
            recruiters = ['TCS', 'Infosys', 'Wipro', 'Cognizant', 'Accenture', 'IBM', 'Microsoft', 'Amazon', 'Google', 'Samsung']
        
        for recruiter_name in recruiters:
            Recruiter.objects.get_or_create(
                course=course,
                name=recruiter_name,
                defaults={'logo': f'courses/recruiters/{recruiter_name.lower().replace(" ", "_")}.png'}
            )

    def _create_why_join(self, course):
        """Create why join reasons"""
        if 'Civil' in course.title:
            reasons = [
                {'title': 'Infrastructure Development', 'description': 'Be part of building the nation\'s infrastructure including smart cities and sustainable structures.'},
                {'title': 'Diverse Career Options', 'description': 'Multiple specializations including structural, environmental, transportation, and geotechnical engineering.'},
                {'title': 'Government Opportunities', 'description': 'Excellent opportunities in government sectors like PWD, Railways, and municipal corporations.'},
                {'title': 'Global Projects', 'description': 'Work on international construction and infrastructure projects worldwide.'},
            ]
        elif 'Electronics & Communication' in course.title:
            reasons = [
                {'title': 'Technology Innovation', 'description': 'Work on cutting-edge technologies like 5G, IoT, and semiconductor design.'},
                {'title': 'High Growth Industry', 'description': 'Electronics and communication industry offers excellent growth and career prospects.'},
                {'title': 'Research Opportunities', 'description': 'Extensive research opportunities in VLSI, embedded systems, and communication.'},
                {'title': 'Global Demand', 'description': 'High demand for ECE professionals in international technology companies.'},
            ]
        elif 'Electrical' in course.title:
            reasons = [
                {'title': 'Energy Sector Growth', 'description': 'Growing opportunities in renewable energy and smart grid technologies.'},
                {'title': 'Industrial Automation', 'description': 'Lead the industry 4.0 revolution with automation and control systems.'},
                {'title': 'Power Systems', 'description': 'Critical role in power generation, transmission, and distribution systems.'},
                {'title': 'Sustainable Future', 'description': 'Contribute to sustainable development through green energy solutions.'},
            ]
        elif 'Mechanical' in course.title:
            reasons = [
                {'title': 'Versatile Engineering', 'description': 'Most versatile engineering branch with applications across all industries.'},
                {'title': 'Manufacturing Innovation', 'description': 'Lead innovation in advanced manufacturing and Industry 4.0 technologies.'},
                {'title': 'Automotive Future', 'description': 'Exciting opportunities in electric vehicles and autonomous vehicle technologies.'},
                {'title': 'Global Industry', 'description': 'Mechanical engineers are in demand across all countries and industries.'},
            ]
        else:
            reasons = [
                {'title': 'Core Engineering', 'description': 'Strong foundation in engineering principles applicable across industries.'},
                {'title': 'Innovation Focus', 'description': 'Develop innovative solutions for real-world engineering challenges.'},
                {'title': 'Industry Ready', 'description': 'Curriculum designed to meet current and future industry requirements.'},
                {'title': 'Research Excellence', 'description': 'Access to advanced research facilities and experienced faculty.'},
            ]
        
        for reason_data in reasons:
            WhyJoin.objects.get_or_create(
                course=course,
                title=reason_data['title'],
                defaults={'description': reason_data['description']}
            )

    def _create_testimonials(self, course):
        """Create student testimonials"""
        testimonials = [
            {
                'name': 'Amit Kumar Singh',
                'position': 'Senior Engineer',
                'company': 'L&T Construction',
                'content': f'The {course.title} program provided me with excellent technical foundation and practical skills. The faculty guidance and industry exposure helped me secure a great position in a leading engineering company.',
                'photo': 'courses/testimonials/amit.jpg'
            },
            {
                'name': 'Priyanka Sharma',
                'position': 'Project Manager',
                'company': 'Siemens',
                'content': f'I am grateful for the comprehensive curriculum and hands-on learning experience in {course.title}. The program prepared me well for leadership roles in the engineering industry.',
                'photo': 'courses/testimonials/priyanka.jpg'
            },
            {
                'name': 'Rajesh Gupta',
                'position': 'Design Engineer',
                'company': 'Tata Motors',
                'content': f'The {course.title} program exceeded my expectations. The combination of theoretical knowledge and practical projects gave me a competitive advantage in my career.',
                'photo': 'courses/testimonials/rajesh.jpg'
            }
        ]
        
        for testimonial_data in testimonials:
            Testimonial.objects.get_or_create(
                course=course,
                name=testimonial_data['name'],
                position=testimonial_data['position'],
                company=testimonial_data['company'],
                defaults={
                    'content': testimonial_data['content'],
                    'photo': testimonial_data['photo']
                }
            )
