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 courses for Roorkee College of Smart Computing'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to seed Smart Computing courses'))
        
        # 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
        courses_data = [
            {
                'title': 'B.Tech. Hons. (CSE)',
                'short_description': 'Honours program in Computer Science & Engineering with advanced curriculum and research opportunities.',
                'overview': 'The B.Tech. Honours in Computer Science & Engineering is an advanced undergraduate program designed for academically outstanding students. This program combines rigorous coursework with research opportunities, preparing students for leadership roles in technology industries or advanced academic pursuits.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Computer Science & Engineering'
            },
            {
                'title': 'B.Tech. Hons. (AI & ML)',
                'short_description': 'Specialized Honours program focusing on Artificial Intelligence and Machine Learning technologies.',
                'overview': 'The B.Tech. Honours in AI & ML is a cutting-edge program that combines computer science fundamentals with advanced artificial intelligence and machine learning concepts. Students will learn deep learning, neural networks, data science, and AI applications across various industries.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Artificial Intelligence & Machine Learning'
            },
            {
                'title': 'B.Tech. Hons. (IOT, Cyber Security including Blockchain Technology / Data Science)',
                'short_description': 'Comprehensive program covering IoT, Cybersecurity, Blockchain, and Data Science technologies.',
                'overview': 'This innovative program integrates Internet of Things (IoT), Cybersecurity, Blockchain Technology, and Data Science. Students will gain expertise in emerging technologies that are shaping the digital future, including secure IoT systems, blockchain applications, and advanced data analytics.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Emerging Technologies'
            },
            {
                'title': 'B.Tech. Hons. LE (CSE)',
                'short_description': 'Lateral Entry Honours program in Computer Science & Engineering for diploma holders.',
                'overview': 'The B.Tech. Honours Lateral Entry program in CSE is designed for diploma holders who want to pursue advanced studies in computer science. This program allows direct admission to the second year while maintaining the honours curriculum standards.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Computer Science & Engineering'
            },
            {
                'title': 'B.Tech. Hons. LE (AI & ML)',
                'short_description': 'Lateral Entry Honours program in Artificial Intelligence & Machine Learning.',
                'overview': 'This lateral entry program provides diploma holders with an opportunity to specialize in AI & ML through an accelerated honours curriculum. Students will focus on advanced AI concepts, machine learning algorithms, and practical applications.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Artificial Intelligence & Machine Learning'
            },
            {
                'title': 'B.Tech. Hons. LE (IOT, Cyber Security including Blockchain Technology / Data Science)',
                'short_description': 'Lateral Entry program covering advanced emerging technologies.',
                'overview': 'This lateral entry honours program focuses on the convergence of IoT, Cybersecurity, Blockchain, and Data Science. Diploma holders can directly join this advanced program to specialize in these high-demand technology areas.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Emerging Technologies'
            },
            {
                'title': 'BCA',
                'short_description': 'Bachelor of Computer Applications - Comprehensive program in computer applications and programming.',
                'overview': 'The BCA program provides a strong foundation in computer applications, programming languages, database management, and software development. This program prepares students for careers in software development, web development, and IT support.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Computer Applications'
            },
            {
                'title': 'BCA (AI & ML / Cyber Security / Data Science)',
                'short_description': 'Specialized BCA program with focus on AI & ML, Cybersecurity, or Data Science.',
                'overview': 'This specialized BCA program allows students to choose from three cutting-edge specializations: Artificial Intelligence & Machine Learning, Cybersecurity, or Data Science. Students will gain expertise in their chosen field while maintaining a strong foundation in computer applications.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Computer Applications'
            },
            {
                'title': 'B.Sc. Computer Science',
                'short_description': 'Undergraduate program in Computer Science with theoretical and practical knowledge.',
                'overview': 'The B.Sc. Computer Science program provides a comprehensive understanding of computer science principles, programming, mathematics, and problem-solving skills. This program is ideal for students interested in software development, research, or pursuing higher studies.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Computer Science'
            },
            {
                'title': 'B.Sc. Computer Science (AI & ML / Cyber Security / Data Science)',
                'short_description': 'Specialized B.Sc. Computer Science with focus on modern technology domains.',
                'overview': 'This specialized B.Sc. program combines computer science fundamentals with specialization in AI & ML, Cybersecurity, or Data Science. Students will develop expertise in their chosen area while maintaining a strong theoretical foundation.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Computer Science'
            },
            {
                'title': 'M.Sc. Computer Science',
                'short_description': 'Advanced postgraduate program in Computer Science with research opportunities.',
                'overview': 'The M.Sc. Computer Science program is designed for graduates who want to deepen their knowledge in computer science. The program includes advanced topics, research methodology, and dissertation work, preparing students for research careers or industry leadership roles.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Computer Science'
            },
            {
                'title': 'B.Sc. Animation & Multimedia',
                'short_description': 'Creative program combining animation, multimedia design, and digital media technologies.',
                'overview': 'The B.Sc. Animation & Multimedia program prepares students for careers in the creative digital industry. Students will learn 2D/3D animation, video editing, graphic design, web design, and multimedia production using industry-standard software and techniques.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Animation & Multimedia'
            },
            {
                'title': 'MCA',
                'short_description': 'Master of Computer Applications - Advanced program in computer applications and software development.',
                'overview': 'The MCA program is a professional postgraduate course in computer applications. It focuses on advanced programming, software engineering, database management, networking, and emerging technologies, preparing students for senior roles in the IT industry.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Computer Applications'
            },
            {
                'title': 'M.Tech. (CS/CSE)',
                'short_description': 'Master of Technology in Computer Science/Computer Science & Engineering.',
                'overview': 'The M.Tech. program in CS/CSE is an advanced engineering degree focusing on specialized areas of computer science and engineering. Students will engage in cutting-edge research and development projects, preparing them for leadership roles in technology industries or academic careers.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Computer Science & Engineering'
            },
            {
                'title': 'Diploma (CSE)',
                'short_description': 'Diploma program in Computer Science & Engineering with practical focus.',
                'overview': 'The Diploma in CSE is a technical program that provides hands-on training in computer science and engineering. This program prepares students for immediate employment in the IT industry or provides a pathway to pursue higher education through lateral entry programs.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Computer Science & Engineering'
            }
        ]
        
        # 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 = [
                'computer,technology', 'artificial,intelligence', 'cybersecurity', 
                'programming,code', 'data,science', 'blockchain', 'animation,design'
            ]
            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 basic highlights
            self._create_course_highlights(course, course_data)
    
    def _create_course_eligibility(self, course, course_data):
        """Create eligibility criteria for the course"""
        if 'LE' in course.title:  # Lateral Entry
            academic_qual = "Diploma in Engineering/Technology in relevant field from a recognized institution."
            minimum_marks = "Minimum 60% aggregate in Diploma (55% for SC/ST/OBC)."
            entrance_exam = "Lateral Entry Entrance Test or merit-based admission."
        elif 'M.Tech' in course.title or 'M.Sc' in course.title or 'MCA' in course.title:
            academic_qual = "Bachelor's degree in relevant field from a recognized university."
            minimum_marks = "Minimum 60% aggregate in qualifying degree (55% for SC/ST/OBC)."
            entrance_exam = "GATE/University Entrance Test or merit-based admission."
        elif 'Diploma' in course.title:
            academic_qual = "10th standard (SSC) from a recognized board."
            minimum_marks = "Minimum 50% aggregate in 10th standard (45% for SC/ST/OBC)."
            entrance_exam = "Merit-based admission or entrance test."
        else:  # Undergraduate courses
            academic_qual = "10+2 (Senior Secondary) with relevant subjects from a recognized board."
            minimum_marks = "Minimum 60% aggregate in 10+2 (55% for SC/ST/OBC)."
            entrance_exam = "JEE Main/State Entrance Test or merit-based admission."
        
        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.Tech' in course.title or 'M.Sc' in course.title:
            domestic_fee = "₹1,80,000 per year"
            international_fee = "$6,000 per year"
        elif 'MCA' in course.title:
            domestic_fee = "₹1,60,000 per year"
            international_fee = "$5,500 per year"
        elif 'B.Tech' in course.title:
            domestic_fee = "₹1,75,000 per year"
            international_fee = "$5,800 per year"
        elif 'BCA' in course.title or 'B.Sc' in course.title:
            domestic_fee = "₹1,20,000 per year"
            international_fee = "$4,000 per year"
        else:  # Diploma
            domestic_fee = "₹80,000 per year"
            international_fee = "$3,000 per year"
        
        CourseFee.objects.update_or_create(
            course=course,
            defaults={
                'domestic': domestic_fee,
                'international': international_fee
            }
        )
    
    def _create_course_highlights(self, course, course_data):
        """Create course highlights"""
        highlights_data = []
        
        if 'AI & ML' in course.title:
            highlights_data = [
                {'title': 'Advanced AI Curriculum', 'description': 'Comprehensive coverage of machine learning, deep learning, and neural networks.', 'icon': 'brain'},
                {'title': 'Hands-on Projects', 'description': 'Real-world AI projects and industry collaborations.', 'icon': 'project-diagram'},
                {'title': 'Research Opportunities', 'description': 'Access to cutting-edge AI research labs and facilities.', 'icon': 'microscope'},
                {'title': 'Industry Connections', 'description': 'Strong ties with leading AI companies and startups.', 'icon': 'handshake'}
            ]
        elif 'Cyber Security' in course.title or 'IOT' in course.title:
            highlights_data = [
                {'title': 'Latest Security Technologies', 'description': 'Learn about modern cybersecurity threats and defense mechanisms.', 'icon': 'shield-alt'},
                {'title': 'Practical Labs', 'description': 'Hands-on experience with security tools and IoT devices.', 'icon': 'tools'},
                {'title': 'Industry Certifications', 'description': 'Preparation for industry-recognized security certifications.', 'icon': 'certificate'},
                {'title': 'Real-world Scenarios', 'description': 'Training with actual security incidents and case studies.', 'icon': 'exclamation-triangle'}
            ]
        elif 'Animation' in course.title:
            highlights_data = [
                {'title': 'Creative Software Training', 'description': 'Master industry-standard animation and design software.', 'icon': 'paint-brush'},
                {'title': 'Portfolio Development', 'description': 'Build a professional portfolio with guided projects.', 'icon': 'folder-open'},
                {'title': 'Industry Mentorship', 'description': 'Learn from experienced professionals in animation industry.', 'icon': 'user-tie'},
                {'title': 'Latest Techniques', 'description': 'Stay updated with current trends in animation and multimedia.', 'icon': 'star'}
            ]
        else:  # General CS/CSE courses
            highlights_data = [
                {'title': 'Comprehensive Curriculum', 'description': 'Complete coverage of computer science fundamentals and advanced topics.', 'icon': 'book'},
                {'title': 'Practical Learning', 'description': 'Extensive lab work and project-based learning approach.', 'icon': 'laptop-code'},
                {'title': 'Industry Ready', 'description': 'Curriculum designed with industry requirements and trends.', 'icon': 'industry'},
                {'title': 'Research Focus', 'description': 'Opportunities for research and innovation in emerging technologies.', 'icon': 'search'}
            ]
        
        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 Smart Computing courses!'))
