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 = 'Seeds the database with B.Tech. in Computer Science & Engineering course data'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to seed B.Tech. CSE course data'))
        
        # Create media directories if they don't exist
        os.makedirs(os.path.join(settings.MEDIA_ROOT, 'courses/banners'), exist_ok=True)
        os.makedirs(os.path.join(settings.MEDIA_ROOT, 'courses/recruiters'), exist_ok=True)
        os.makedirs(os.path.join(settings.MEDIA_ROOT, 'courses/gallery'), exist_ok=True)
        os.makedirs(os.path.join(settings.MEDIA_ROOT, 'courses/testimonials'), 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:
                    # Extract filename from URL
                    filename = os.path.basename(url.split('?')[0])
                    if not filename or '.' not in filename:
                        filename = f"{field_name}.jpg"
                    
                    # Create ContentFile from response content
                    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
        
        # Create Course
        course_data = {
            'title': 'B.Tech. in Computer Science & Engineering',
            'slug': 'btech-computer-science-engineering',
            'short_description': 'A comprehensive program covering computer science fundamentals, software development, and engineering principles to prepare students for careers in technology.',
            'overview': (
                'The B.Tech. in Computer Science & Engineering program is designed to provide students with a strong foundation in computer science theory, '
                'programming skills, and engineering principles. The curriculum covers a wide range of topics including algorithms, data structures, '
                'operating systems, database management, artificial intelligence, machine learning, and software engineering.\n\n'
                'Students will gain hands-on experience through laboratory work, projects, and internships, preparing them for careers in software development, '
                'system administration, data science, and other technology fields. The program also emphasizes problem-solving, critical thinking, and communication skills '
                'that are essential for success in the industry.\n\n'
                'With state-of-the-art facilities, experienced faculty, and industry connections, our B.Tech. CSE program ensures that graduates are well-equipped to '
                'meet the challenges of the rapidly evolving technology landscape.'
            ),
            'duration': '4 Years (8 Semesters)',
            'category': 'Computer Science & Engineering',
            'banner_image_url': 'https://source.unsplash.com/random/1200x600/?computer,programming'
        }
        
        # Download banner image
        banner_image = save_image_from_url(course_data['banner_image_url'], 'cse_banner')
        
        # Create or update course
        course, created = Course.objects.update_or_create(
            slug=course_data['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 Eligibility
        eligibility_data = {
            'academic_qualification': (
                '10+2 (Senior Secondary) with Physics, Chemistry, and Mathematics as compulsory subjects from a recognized board or equivalent.\n\n'
                'Diploma holders in any branch of Engineering/Technology from a recognized institution are also eligible for admission through lateral entry into the second year.'
            ),
            'minimum_marks': (
                'General Category: Minimum 60% aggregate in PCM (Physics, Chemistry, Mathematics) at 10+2 level.\n'
                'SC/ST/OBC Category: Minimum 55% aggregate in PCM at 10+2 level.\n'
                'For lateral entry: Minimum 60% aggregate in Diploma.'
            ),
            'entrance_exam': (
                'Admission is based on merit in national/state level entrance examinations such as:\n'
                '- JEE Main (Joint Entrance Examination)\n'
                '- State Engineering Entrance Examinations\n'
                '- University-level Engineering Entrance Test\n\n'
                'Candidates must qualify in the entrance examination and participate in the counseling process for seat allocation.'
            )
        }
        
        CourseEligibility.objects.update_or_create(
            course=course,
            defaults=eligibility_data
        )
        
        # Create Course Fee
        course_fee, _ = CourseFee.objects.update_or_create(
            course=course,
            defaults={
                'domestic': '₹1,50,000 per year (approximately)',
                'international': '$5,000 per year (approximately)'
            }
        )
        
        # Create Fee Details
        fee_details = [
            {
                'fee_head': 'Tuition Fee',
                'first_year': '₹1,00,000',
                'second_year': '₹1,00,000',
                'third_year': '₹1,10,000',
                'fourth_year': '₹1,10,000',
                'is_one_time': False
            },
            {
                'fee_head': 'Development Fee',
                'first_year': '₹15,000',
                'second_year': '₹15,000',
                'third_year': '₹15,000',
                'fourth_year': '₹15,000',
                'is_one_time': False
            },
            {
                'fee_head': 'Examination Fee',
                'first_year': '₹10,000',
                'second_year': '₹10,000',
                'third_year': '₹10,000',
                'fourth_year': '₹10,000',
                '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': 'Security Deposit (Refundable)',
                'first_year': '₹20,000',
                'second_year': '₹0',
                'third_year': '₹0',
                'fourth_year': '₹0',
                'is_one_time': True
            }
        ]
        
        # Clear existing fee details
        FeeDetail.objects.filter(course_fee=course_fee).delete()
        
        # Create new fee details
        for detail in fee_details:
            FeeDetail.objects.create(
                course_fee=course_fee,
                **detail
            )
        
        # Create Hostel Fee
        HostelFee.objects.update_or_create(
            course=course,
            defaults={
                'fee_per_year': '₹75,000',
                'ac_room_additional': '₹25,000',
                'security_deposit': '₹10,000',
                'notes': 'Hostel fees include accommodation, mess charges, and basic amenities. AC rooms are subject to availability. Hostel allocation is based on merit and distance from hometown.'
            }
        )
        
        # Create Semesters and Subjects
        semesters_data = [
            {
                'name': 'Semester 1',
                'number': 1,
                'subjects': [
                    {
                        'code': 'CS101',
                        'name': 'Introduction to Programming',
                        'credits': 4,
                        'description': 'Fundamentals of programming using C, including variables, data types, control structures, functions, arrays, and basic algorithms.'
                    },
                    {
                        'code': 'MA101',
                        'name': 'Engineering Mathematics I',
                        'credits': 4,
                        'description': 'Calculus, differential equations, matrices, and their applications in engineering problems.'
                    },
                    {
                        'code': 'PH101',
                        'name': 'Engineering Physics',
                        'credits': 3,
                        'description': 'Mechanics, waves, optics, and modern physics concepts relevant to engineering applications.'
                    },
                    {
                        'code': 'CH101',
                        'name': 'Engineering Chemistry',
                        'credits': 3,
                        'description': 'Basic concepts of chemistry including thermodynamics, electrochemistry, and materials science.'
                    },
                    {
                        'code': 'HU101',
                        'name': 'Communication Skills',
                        'credits': 2,
                        'description': 'English language proficiency, technical writing, presentation skills, and professional communication.'
                    },
                    {
                        'code': 'ME101',
                        'name': 'Engineering Drawing',
                        'credits': 3,
                        'description': 'Principles of engineering drawing, orthographic projections, dimensioning, and CAD basics.'
                    }
                ]
            },
            {
                'name': 'Semester 2',
                'number': 2,
                'subjects': [
                    {
                        'code': 'CS102',
                        'name': 'Data Structures',
                        'credits': 4,
                        'description': 'Implementation and application of arrays, linked lists, stacks, queues, trees, graphs, and various searching and sorting algorithms.'
                    },
                    {
                        'code': 'MA102',
                        'name': 'Engineering Mathematics II',
                        'credits': 4,
                        'description': 'Probability, statistics, numerical methods, and their applications in computer science.'
                    },
                    {
                        'code': 'EC101',
                        'name': 'Digital Electronics',
                        'credits': 3,
                        'description': 'Number systems, Boolean algebra, logic gates, combinational and sequential circuits, and digital system design.'
                    },
                    {
                        'code': 'CS103',
                        'name': 'Object-Oriented Programming',
                        'credits': 4,
                        'description': 'Object-oriented programming concepts using C++ or Java, including classes, objects, inheritance, polymorphism, and encapsulation.'
                    },
                    {
                        'code': 'HU102',
                        'name': 'Environmental Studies',
                        'credits': 2,
                        'description': 'Environmental issues, sustainability, and the role of technology in environmental protection.'
                    },
                    {
                        'code': 'CS104',
                        'name': 'Programming Lab',
                        'credits': 2,
                        'description': 'Practical implementation of programming concepts and data structures.'
                    }
                ]
            },
            {
                'name': 'Semester 3',
                'number': 3,
                'subjects': [
                    {
                        'code': 'CS201',
                        'name': 'Computer Organization and Architecture',
                        'credits': 4,
                        'description': 'Computer organization, CPU design, memory hierarchy, I/O systems, and performance evaluation.'
                    },
                    {
                        'code': 'CS202',
                        'name': 'Database Management Systems',
                        'credits': 4,
                        'description': 'Database concepts, ER modeling, relational model, SQL, normalization, transaction management, and concurrency control.'
                    },
                    {
                        'code': 'CS203',
                        'name': 'Discrete Mathematics',
                        'credits': 3,
                        'description': 'Sets, relations, functions, graph theory, combinatorics, and mathematical reasoning for computer science.'
                    },
                    {
                        'code': 'CS204',
                        'name': 'Operating Systems',
                        'credits': 4,
                        'description': 'Process management, memory management, file systems, I/O management, and security in operating systems.'
                    },
                    {
                        'code': 'CS205',
                        'name': 'Web Technologies',
                        'credits': 3,
                        'description': 'HTML, CSS, JavaScript, client-server architecture, and web application development.'
                    },
                    {
                        'code': 'CS206',
                        'name': 'DBMS Lab',
                        'credits': 2,
                        'description': 'Practical implementation of database concepts using SQL and database management systems.'
                    }
                ]
            },
            {
                'name': 'Semester 4',
                'number': 4,
                'subjects': [
                    {
                        'code': 'CS207',
                        'name': 'Design and Analysis of Algorithms',
                        'credits': 4,
                        'description': 'Algorithm design techniques, complexity analysis, greedy algorithms, dynamic programming, and NP-completeness.'
                    },
                    {
                        'code': 'CS208',
                        'name': 'Computer Networks',
                        'credits': 4,
                        'description': 'Network architectures, protocols, routing algorithms, network security, and application layer protocols.'
                    },
                    {
                        'code': 'CS209',
                        'name': 'Software Engineering',
                        'credits': 3,
                        'description': 'Software development life cycle, requirements engineering, design patterns, testing, and project management.'
                    },
                    {
                        'code': 'CS210',
                        'name': 'Theory of Computation',
                        'credits': 3,
                        'description': 'Automata theory, formal languages, Turing machines, computability, and complexity theory.'
                    },
                    {
                        'code': 'CS211',
                        'name': 'Python Programming',
                        'credits': 3,
                        'description': 'Python syntax, data structures, object-oriented programming in Python, and application development.'
                    },
                    {
                        'code': 'CS212',
                        'name': 'Networks Lab',
                        'credits': 2,
                        'description': 'Practical implementation of networking concepts, protocols, and network programming.'
                    }
                ]
            },
            {
                'name': 'Semester 5',
                'number': 5,
                'subjects': [
                    {
                        'code': 'CS301',
                        'name': 'Artificial Intelligence',
                        'credits': 4,
                        'description': 'Problem-solving, knowledge representation, reasoning, machine learning, and natural language processing.'
                    },
                    {
                        'code': 'CS302',
                        'name': 'Compiler Design',
                        'credits': 4,
                        'description': 'Lexical analysis, parsing, semantic analysis, code generation, and optimization techniques.'
                    },
                    {
                        'code': 'CS303',
                        'name': 'Mobile Application Development',
                        'credits': 3,
                        'description': 'Android/iOS app development, UI design, data storage, and integration with web services.'
                    },
                    {
                        'code': 'CS304',
                        'name': 'Information Security',
                        'credits': 3,
                        'description': 'Cryptography, network security, authentication, access control, and security protocols.'
                    },
                    {
                        'code': 'CS305',
                        'name': 'Professional Elective I',
                        'credits': 3,
                        'description': 'Specialized course based on student interest and industry trends.'
                    },
                    {
                        'code': 'CS306',
                        'name': 'AI and Mobile App Development Lab',
                        'credits': 2,
                        'description': 'Practical implementation of AI algorithms and mobile application development.'
                    }
                ]
            },
            {
                'name': 'Semester 6',
                'number': 6,
                'subjects': [
                    {
                        'code': 'CS307',
                        'name': 'Machine Learning',
                        'credits': 4,
                        'description': 'Supervised and unsupervised learning, neural networks, deep learning, and applications.'
                    },
                    {
                        'code': 'CS308',
                        'name': 'Cloud Computing',
                        'credits': 3,
                        'description': 'Cloud architectures, virtualization, service models, deployment models, and cloud security.'
                    },
                    {
                        'code': 'CS309',
                        'name': 'Big Data Analytics',
                        'credits': 3,
                        'description': 'Hadoop ecosystem, MapReduce, Spark, NoSQL databases, and data visualization.'
                    },
                    {
                        'code': 'CS310',
                        'name': 'Professional Elective II',
                        'credits': 3,
                        'description': 'Specialized course based on student interest and industry trends.'
                    },
                    {
                        'code': 'CS311',
                        'name': 'Open Elective',
                        'credits': 3,
                        'description': 'Course from other departments to broaden knowledge base.'
                    },
                    {
                        'code': 'CS312',
                        'name': 'Machine Learning Lab',
                        'credits': 2,
                        'description': 'Practical implementation of machine learning algorithms and projects.'
                    }
                ]
            },
            {
                'name': 'Semester 7',
                'number': 7,
                'subjects': [
                    {
                        'code': 'CS401',
                        'name': 'Internet of Things',
                        'credits': 3,
                        'description': 'IoT architectures, protocols, sensors, actuators, and IoT application development.'
                    },
                    {
                        'code': 'CS402',
                        'name': 'Professional Elective III',
                        'credits': 3,
                        'description': 'Specialized course based on student interest and industry trends.'
                    },
                    {
                        'code': 'CS403',
                        'name': 'Professional Elective IV',
                        'credits': 3,
                        'description': 'Specialized course based on student interest and industry trends.'
                    },
                    {
                        'code': 'HU401',
                        'name': 'Engineering Economics and Management',
                        'credits': 3,
                        'description': 'Economic analysis, financial management, and project management for engineers.'
                    },
                    {
                        'code': 'CS404',
                        'name': 'Project Phase I',
                        'credits': 6,
                        'description': 'First phase of the capstone project involving problem definition, literature review, and preliminary design.'
                    }
                ]
            },
            {
                'name': 'Semester 8',
                'number': 8,
                'subjects': [
                    {
                        'code': 'CS405',
                        'name': 'Professional Elective V',
                        'credits': 3,
                        'description': 'Specialized course based on student interest and industry trends.'
                    },
                    {
                        'code': 'CS406',
                        'name': 'Project Phase II',
                        'credits': 12,
                        'description': 'Final phase of the capstone project involving implementation, testing, and documentation.'
                    },
                    {
                        'code': 'CS407',
                        'name': 'Seminar',
                        'credits': 2,
                        'description': 'Presentation on emerging technologies and research in computer science.'
                    }
                ]
            }
        ]
        
        # Clear existing semesters and subjects
        for semester in Semester.objects.filter(course=course):
            Subject.objects.filter(semester=semester).delete()
        Semester.objects.filter(course=course).delete()
        
        # Create new semesters and subjects
        for semester_data in semesters_data:
            semester = Semester.objects.create(
                course=course,
                name=semester_data['name'],
                number=semester_data['number']
            )
            
            for subject_data in semester_data['subjects']:
                Subject.objects.create(
                    semester=semester,
                    **subject_data
                )
        
        # Create Career Prospects
        career_prospects = [
            {
                'title': 'Software Developer/Engineer',
                'salary_range': '₹5,00,000 - ₹15,00,000 per annum',
                'description': 'Design, develop, and maintain software applications using various programming languages and frameworks.'
            },
            {
                'title': 'Data Scientist/Analyst',
                'salary_range': '₹6,00,000 - ₹18,00,000 per annum',
                'description': 'Analyze and interpret complex data to help organizations make better decisions.'
            },
            {
                'title': 'Machine Learning Engineer',
                'salary_range': '₹8,00,000 - ₹20,00,000 per annum',
                'description': 'Develop and implement machine learning models and algorithms for various applications.'
            },
            {
                'title': 'Cloud Computing Specialist',
                'salary_range': '₹7,00,000 - ₹16,00,000 per annum',
                'description': 'Design, implement, and manage cloud-based systems and infrastructure.'
            },
            {
                'title': 'DevOps Engineer',
                'salary_range': '₹6,00,000 - ₹18,00,000 per annum',
                'description': 'Combine software development and IT operations to improve the development lifecycle.'
            },
            {
                'title': 'Cybersecurity Analyst',
                'salary_range': '₹7,00,000 - ₹20,00,000 per annum',
                'description': 'Protect computer systems and networks from information disclosure, theft, or damage.'
            },
            {
                'title': 'Full Stack Developer',
                'salary_range': '₹6,00,000 - ₹16,00,000 per annum',
                'description': 'Develop both client and server software for web applications.'
            },
            {
                'title': 'Mobile Application Developer',
                'salary_range': '₹5,00,000 - ₹15,00,000 per annum',
                'description': 'Design and develop applications for mobile devices on platforms like Android and iOS.'
            }
        ]
        
        # Clear existing career prospects
        CareerProspect.objects.filter(course=course).delete()
        
        # Create new career prospects
        for prospect in career_prospects:
            CareerProspect.objects.create(
                course=course,
                **prospect
            )
        
        # Create Admission Steps
        admission_steps = [
            {
                'title': 'Entrance Examination',
                'description': 'Appear for JEE Main or state-level engineering entrance examination.',
                'order': 1
            },
            {
                'title': 'Counseling Registration',
                'description': 'Register for the counseling process conducted by the respective examination authority.',
                'order': 2
            },
            {
                'title': 'Choice Filling',
                'description': 'Fill in your college and branch preferences during the counseling process.',
                'order': 3
            },
            {
                'title': 'Seat Allotment',
                'description': 'Seats are allotted based on rank, category, and availability.',
                'order': 4
            },
            {
                'title': 'Fee Payment',
                'description': 'Pay the admission fee as specified in the allotment letter.',
                'order': 5
            },
            {
                'title': 'Document Verification',
                'description': 'Submit original documents for verification at the allotted institution.',
                'order': 6
            },
            {
                'title': 'Admission Confirmation',
                'description': 'Receive admission confirmation letter and complete the registration process.',
                'order': 7
            }
        ]
        
        # Clear existing admission steps
        AdmissionStep.objects.filter(course=course).delete()
        
        # Create new admission steps
        for step in admission_steps:
            AdmissionStep.objects.create(
                course=course,
                **step
            )
        
        # Create Direct Admission
        DirectAdmission.objects.update_or_create(
            course=course,
            defaults={
                'description': (
                    'A limited number of seats are available for direct admission under the management quota. '
                    'Candidates must have a minimum of 60% aggregate in PCM at 10+2 level. '
                    'Selection is based on merit and personal interview. '
                    'Contact the admission office for more details on the direct admission process and fee structure.'
                ),
                'is_available': True
            }
        )
        
        # Create Recruiters
        recruiters = [
            {
                'name': 'Microsoft',
                'logo_url': 'https://logo.clearbit.com/microsoft.com'
            },
            {
                'name': 'Google',
                'logo_url': 'https://logo.clearbit.com/google.com'
            },
            {
                'name': 'Amazon',
                'logo_url': 'https://logo.clearbit.com/amazon.com'
            },
            {
                'name': 'IBM',
                'logo_url': 'https://logo.clearbit.com/ibm.com'
            },
            {
                'name': 'Infosys',
                'logo_url': 'https://logo.clearbit.com/infosys.com'
            },
            {
                'name': 'TCS',
                'logo_url': 'https://logo.clearbit.com/tcs.com'
            },
            {
                'name': 'Wipro',
                'logo_url': 'https://logo.clearbit.com/wipro.com'
            },
            {
                'name': 'Accenture',
                'logo_url': 'https://logo.clearbit.com/accenture.com'
            },
            {
                'name': 'Oracle',
                'logo_url': 'https://logo.clearbit.com/oracle.com'
            },
            {
                'name': 'Intel',
                'logo_url': 'https://logo.clearbit.com/intel.com'
            }
        ]
        
        # Clear existing recruiters
        Recruiter.objects.filter(course=course).delete()
        
        # Create new recruiters
        for recruiter_data in recruiters:
            logo = save_image_from_url(recruiter_data['logo_url'], f"recruiter_{slugify(recruiter_data['name'])}")
            
            recruiter = Recruiter.objects.create(
                course=course,
                name=recruiter_data['name']
            )
            
            if logo:
                recruiter.logo = logo
                recruiter.save()
        
        # Create Why Join
        why_join = [
            {
                'title': 'Industry-Aligned Curriculum',
                'description': 'Our curriculum is regularly updated in consultation with industry experts to ensure it meets the current and future needs of the technology sector.'
            },
            {
                'title': 'Experienced Faculty',
                'description': 'Learn from highly qualified faculty members with academic and industry experience who are dedicated to student success.'
            },
            {
                'title': 'State-of-the-Art Infrastructure',
                'description': 'Access to modern computer labs, high-speed internet, specialized software, and digital learning resources.'
            },
            {
                'title': 'Industry Partnerships',
                'description': 'Collaborations with leading technology companies for internships, projects, and placement opportunities.'
            },
            {
                'title': 'Research Opportunities',
                'description': 'Engage in cutting-edge research projects under faculty guidance in areas like AI, machine learning, and cybersecurity.'
            },
            {
                'title': 'Hands-on Learning',
                'description': 'Practical approach to education with emphasis on projects, lab work, and real-world problem-solving.'
            },
            {
                'title': 'Excellent Placement Record',
                'description': 'Consistent placement record with students securing positions in top technology companies with competitive packages.'
            }
        ]
        
        # Clear existing why join
        WhyJoin.objects.filter(course=course).delete()
        
        # Create new why join
        for item in why_join:
            WhyJoin.objects.create(
                course=course,
                **item
            )
        
        # Create Course Highlights
        highlights = [
            {
                'title': 'AICTE Approved',
                'description': 'Program approved by the All India Council for Technical Education.',
                'icon': 'check-circle'
            },
            {
                'title': 'Industry Internships',
                'description': 'Mandatory internship program with leading technology companies.',
                'icon': 'briefcase'
            },
            {
                'title': 'Modern Labs',
                'description': 'Well-equipped laboratories with the latest hardware and software.',
                'icon': 'server'
            },
            {
                'title': 'Expert Faculty',
                'description': 'Highly qualified faculty with industry and research experience.',
                'icon': 'users'
            },
            {
                'title': 'Placement Assistance',
                'description': 'Dedicated placement cell with excellent industry connections.',
                'icon': 'award'
            },
            {
                'title': 'Research Focus',
                'description': 'Opportunities to participate in research projects and publications.',
                'icon': 'search'
            }
        ]
        
        # Clear existing highlights
        CourseHighlight.objects.filter(course=course).delete()
        
        # Create new highlights
        for highlight in highlights:
            CourseHighlight.objects.create(
                course=course,
                **highlight
            )
        
        # Create Course Images
        course_images = [
            {
                'title': 'Computer Lab',
                'image_url': 'https://source.unsplash.com/random/800x600/?computer,lab',
                'is_banner': False
            },
            {
                'title': 'Programming Class',
                'image_url': 'https://source.unsplash.com/random/800x600/?programming,class',
                'is_banner': False
            },
            {
                'title': 'Student Project',
                'image_url': 'https://source.unsplash.com/random/800x600/?student,project',
                'is_banner': False
            },
            {
                'title': 'Campus Technology Center',
                'image_url': 'https://source.unsplash.com/random/800x600/?campus,technology',
                'is_banner': False
            }
        ]
        
        # Clear existing course images
        CourseImage.objects.filter(course=course).delete()
        
        # Create new course images
        for image_data in course_images:
            image = save_image_from_url(image_data['image_url'], f"course_{slugify(image_data['title'])}")
            
            course_image = CourseImage.objects.create(
                course=course,
                title=image_data['title'],
                is_banner=image_data['is_banner']
            )
            
            if image:
                course_image.image = image
                course_image.save()
        
        # Create Testimonials
        testimonials = [
            {
                'name': 'Rahul Sharma',
                'position': 'Software Engineer',
                'company': 'Microsoft',
                'content': 'The B.Tech CSE program provided me with a strong foundation in computer science concepts and practical skills that have been invaluable in my career. The faculty support and industry exposure helped me secure a position at Microsoft.',
                'photo_url': 'https://source.unsplash.com/random/300x300/?indian,man'
            },
            {
                'name': 'Priya Patel',
                'position': 'Data Scientist',
                'company': 'Amazon',
                'content': 'I am grateful for the comprehensive curriculum that covered both traditional computer science and emerging technologies like AI and machine learning. The project-based learning approach prepared me well for real-world challenges.',
                'photo_url': 'https://source.unsplash.com/random/300x300/?indian,woman'
            },
            {
                'name': 'Amit Kumar',
                'position': 'Full Stack Developer',
                'company': 'Google',
                'content': 'The emphasis on practical learning and industry projects gave me an edge during placements. The programming skills and problem-solving abilities I developed during the program have been crucial for my success as a developer.',
                'photo_url': 'https://source.unsplash.com/random/300x300/?indian,developer'
            }
        ]
        
        # Clear existing testimonials
        Testimonial.objects.filter(course=course).delete()
        
        # Create new testimonials
        for testimonial_data in testimonials:
            photo = save_image_from_url(testimonial_data['photo_url'], f"testimonial_{slugify(testimonial_data['name'])}")
            
            testimonial = Testimonial.objects.create(
                course=course,
                name=testimonial_data['name'],
                position=testimonial_data['position'],
                company=testimonial_data['company'],
                content=testimonial_data['content']
            )
            
            if photo:
                testimonial.photo = photo
                testimonial.save()
        
        self.stdout.write(self.style.SUCCESS('Successfully seeded B.Tech. CSE course data'))