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 Engineering'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to seed Engineering 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 for engineering
        courses_data = [
            # B.Tech Honours Programs
            {
                'title': 'B.Tech. Hons. (Civil Engineering)',
                'short_description': 'Comprehensive program in Civil Engineering covering structural design, construction management, and infrastructure development.',
                'overview': 'The B.Tech. Honours in Civil Engineering is designed to provide students with a strong foundation in civil engineering principles, structural analysis, construction technology, and project management. Students will learn about design of buildings, bridges, roads, water supply systems, and environmental engineering. The program emphasizes both theoretical knowledge and practical skills through laboratory work, field visits, and industry projects.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Civil Engineering'
            },
            {
                'title': 'B.Tech. Hons. (Electronics & Communication Engineering)',
                'short_description': 'Advanced program in ECE focusing on electronics design, communication systems, and signal processing.',
                'overview': 'The B.Tech. Honours in Electronics & Communication Engineering provides comprehensive training in electronic circuits, digital systems, communication networks, and signal processing. Students will gain expertise in areas such as VLSI design, embedded systems, wireless communication, and optical communication. The program includes extensive laboratory work and industry-oriented projects to ensure practical skills development.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Electronics & Communication Engineering'
            },
            {
                'title': 'B.Tech. Hons. (Electrical & Electronics Engineering)',
                'short_description': 'Comprehensive program covering power systems, control systems, and electrical machine design.',
                'overview': 'The B.Tech. Honours in Electrical & Electronics Engineering focuses on power generation, transmission, distribution, electrical machines, control systems, and power electronics. Students will learn about renewable energy systems, smart grids, electric vehicles, and industrial automation. The curriculum combines theoretical foundations with hands-on experience in well-equipped laboratories and real-world projects.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Electrical & Electronics Engineering'
            },
            {
                'title': 'B.Tech. Hons. (Mechanical Engineering)',
                'short_description': 'Advanced mechanical engineering program covering design, manufacturing, and thermal systems.',
                'overview': 'The B.Tech. Honours in Mechanical Engineering provides comprehensive education in mechanical design, manufacturing processes, thermodynamics, fluid mechanics, and materials science. Students will gain expertise in CAD/CAM, robotics, automotive engineering, and industrial automation. The program emphasizes problem-solving skills and innovation through practical projects and industry collaborations.',
                'duration': '4 Years (8 Semesters)',
                'category': 'Mechanical Engineering'
            },
            
            # B.Tech Lateral Entry Programs
            {
                'title': 'B.Tech. Hons. LE (Civil Engineering)',
                'short_description': 'Lateral entry program for diploma holders in Civil Engineering with advanced curriculum.',
                'overview': 'The B.Tech. Honours Lateral Entry program in Civil Engineering is designed for diploma holders who want to pursue advanced studies in civil engineering. This accelerated program allows direct admission to the second year while maintaining honours curriculum standards. Students will focus on advanced topics in structural engineering, transportation, and environmental systems.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Civil Engineering'
            },
            {
                'title': 'B.Tech. Hons. LE (Electronics & Communication Engineering)',
                'short_description': 'Lateral entry program for ECE diploma holders with focus on advanced communication systems.',
                'overview': 'This lateral entry honours program provides diploma holders with an opportunity to specialize in advanced electronics and communication engineering. Students will focus on cutting-edge topics such as 5G communication, IoT systems, embedded design, and VLSI technology through an accelerated curriculum.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Electronics & Communication Engineering'
            },
            {
                'title': 'B.Tech. Hons. LE (Electrical & Electronics Engineering)',
                'short_description': 'Lateral entry program focusing on advanced power systems and industrial automation.',
                'overview': 'The lateral entry honours program in EEE is designed for diploma holders who want to advance their careers in electrical engineering. The curriculum focuses on modern power systems, renewable energy, smart grids, and industrial automation technologies.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Electrical & Electronics Engineering'
            },
            {
                'title': 'B.Tech. Hons. LE (Mechanical Engineering)',
                'short_description': 'Lateral entry program covering advanced manufacturing and design technologies.',
                'overview': 'This lateral entry programme provides diploma holders with advanced knowledge in mechanical engineering. Students will focus on modern manufacturing techniques, automation, robotics, and sustainable engineering practices through hands-on projects and industry exposure.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Mechanical Engineering'
            },
            
            # M.Tech Programs
            {
                'title': 'M.Tech. (Civil Engineering)',
                'short_description': 'Advanced postgraduate program in Civil Engineering with specialization options.',
                'overview': 'The M.Tech. in Civil Engineering is a research-oriented program that provides advanced knowledge in structural engineering, geotechnical engineering, transportation engineering, or environmental engineering. Students will engage in cutting-edge research projects and develop expertise in specialized areas of civil engineering.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Civil Engineering'
            },
            {
                'title': 'M.Tech. (Electronics & Communication Engineering)',
                'short_description': 'Research-focused program in advanced ECE topics and emerging technologies.',
                'overview': 'The M.Tech. in ECE program focuses on advanced research in areas such as VLSI design, signal processing, communication systems, and embedded systems. Students will work on cutting-edge projects and contribute to technological innovation in the electronics and communication field.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Electronics & Communication Engineering'
            },
            {
                'title': 'M.Tech. (Electrical & Electronics Engineering)',
                'short_description': 'Advanced program focusing on power systems, control engineering, and renewable energy.',
                'overview': 'The M.Tech. in EEE program provides advanced knowledge in power systems analysis, control engineering, power electronics, and renewable energy systems. Students will conduct research in areas such as smart grids, electric vehicles, and sustainable energy technologies.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Electrical & Electronics Engineering'
            },
            {
                'title': 'M.Tech. (Mechanical Engineering)',
                'short_description': 'Research-oriented program in advanced mechanical engineering and manufacturing.',
                'overview': 'The M.Tech. in Mechanical Engineering program focuses on advanced topics in design engineering, manufacturing technology, thermal engineering, and materials science. Students will engage in research projects related to Industry 4.0, sustainable manufacturing, and advanced materials.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Mechanical Engineering'
            },
            
            # Diploma Programs
            {
                'title': 'Diploma (Civil Engineering)',
                'short_description': 'Technical diploma program providing practical skills in civil engineering.',
                'overview': 'The Diploma in Civil Engineering is a hands-on program that prepares students for careers as civil engineering technicians. Students will learn practical skills in surveying, construction technology, building materials, and project execution. The program emphasizes practical training and industry readiness.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Civil Engineering'
            },
            {
                'title': 'Diploma (Electronics & Electronics Engineering)',
                'short_description': 'Technical diploma focusing on electronics systems and electrical installations.',
                'overview': 'The Diploma in EEE program provides practical training in electrical systems, electronics circuits, and power distribution. Students will gain hands-on experience in electrical installations, maintenance, and troubleshooting of electrical and electronic systems.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Electrical & Electronics Engineering'
            },
            {
                'title': 'Diploma (Mechanical Engineering)',
                'short_description': 'Practical diploma program in mechanical systems and manufacturing processes.',
                'overview': 'The Diploma in Mechanical Engineering provides practical skills in mechanical systems, manufacturing processes, and maintenance engineering. Students will gain hands-on experience with machine tools, manufacturing processes, and mechanical system design.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Mechanical Engineering'
            },
            {
                'title': 'Diploma (Electronics & Communication Engineering)',
                'short_description': 'Technical program focusing on electronics and communication system maintenance.',
                'overview': 'The Diploma in ECE program provides practical training in electronics circuits, communication systems, and digital electronics. Students will learn to install, maintain, and troubleshoot electronic and communication equipment used in various industries.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Electronics & Communication Engineering'
            },
            
            # Ph.D. Programs
            {
                'title': 'Ph.D. (Civil Engineering)',
                'short_description': 'Doctoral research program in advanced civil engineering topics.',
                'overview': 'The Ph.D. in Civil Engineering is a research-intensive program for students interested in pursuing careers in academia or advanced research. Students will conduct original research in areas such as structural engineering, environmental engineering, transportation, or geotechnical engineering under the guidance of experienced faculty.',
                'duration': '3-5 Years',
                'category': 'Civil Engineering'
            },
            {
                'title': 'Ph.D. (Electrical & Electronics Engineering)',
                'short_description': 'Doctoral program in advanced electrical engineering research.',
                'overview': 'The Ph.D. in EEE program focuses on advanced research in power systems, control engineering, power electronics, and renewable energy. Students will contribute to cutting-edge research and develop innovative solutions for electrical engineering challenges.',
                'duration': '3-5 Years',
                'category': 'Electrical & Electronics Engineering'
            },
            {
                'title': 'Ph.D. (Mechanical Engineering)',
                'short_description': 'Research doctorate in advanced mechanical engineering and manufacturing.',
                'overview': 'The Ph.D. in Mechanical Engineering program enables students to conduct advanced research in areas such as advanced manufacturing, materials science, thermal systems, and mechanical design. Students will work on innovative projects that contribute to the advancement of mechanical engineering knowledge.',
                'duration': '3-5 Years',
                'category': 'Mechanical Engineering'
            },
            {
                'title': 'Ph.D. (Electronics & Communication Engineering)',
                'short_description': 'Doctoral research program in advanced ECE and emerging technologies.',
                'overview': 'The Ph.D. in ECE program focuses on cutting-edge research in areas such as wireless communication, VLSI design, signal processing, and emerging technologies. Students will contribute to technological innovation and advance the frontiers of electronics and communication engineering.',
                'duration': '3-5 Years',
                'category': 'Electronics & Communication 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 = [
                'civil,engineering,construction', 'electronics,circuit,technology', 
                'electrical,power,energy', 'mechanical,engineering,machines',
                'engineering,blueprint', 'industrial,manufacturing'
            ]
            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 'Ph.D' in course.title:
            academic_qual = "Master's degree (M.Tech/M.E./M.Sc.) in relevant engineering field from a recognized university."
            minimum_marks = "Minimum 60% aggregate in qualifying degree (55% for SC/ST/OBC). GATE qualification preferred."
            entrance_exam = "University Research Entrance Test, Interview, and Research Proposal evaluation."
        elif 'M.Tech' in course.title:
            academic_qual = "Bachelor's degree in relevant engineering field from a recognized university."
            minimum_marks = "Minimum 60% aggregate in qualifying degree (55% for SC/ST/OBC)."
            entrance_exam = "GATE score or University Entrance Test with personal interview."
        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 state polytechnic entrance test."
        else:  # B.Tech courses
            academic_qual = "10+2 (Senior Secondary) with Physics, Chemistry, and Mathematics from a recognized board."
            minimum_marks = "Minimum 60% aggregate in PCM at 10+2 level (55% for SC/ST/OBC)."
            entrance_exam = "JEE Main/State Engineering Entrance Test or university entrance examination."
        
        CourseEligibility.objects.update_or_create(
            course=course,
            defaults={
                'academic_qualification': academic_qual,
                'minimum_marks': minimum_marks,
                'entrance_exam': entrance_exam
            }
        )
    
    def _create_course_fees(self, course, course_data):
        """Create fee structure for the course"""
        # Base fees based on course type
        if 'Ph.D' in course.title:
            domestic_fee = "₹60,000 per year"
            international_fee = "$2,500 per year"
        elif 'M.Tech' in course.title:
            domestic_fee = "₹2,00,000 per year"
            international_fee = "$7,000 per year"
        elif 'B.Tech' in course.title:
            domestic_fee = "₹1,85,000 per year"
            international_fee = "$6,200 per year"
        else:  # Diploma
            domestic_fee = "₹85,000 per year"
            international_fee = "$3,200 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 'Civil' in course.title:
            highlights_data = [
                {'title': 'Infrastructure Focus', 'description': 'Comprehensive training in building design, transportation systems, and urban planning.', 'icon': 'building'},
                {'title': 'Industry Projects', 'description': 'Real-world construction and infrastructure projects with industry partners.', 'icon': 'project-diagram'},
                {'title': 'Advanced Labs', 'description': 'State-of-the-art structural, materials, and surveying laboratories.', 'icon': 'flask'},
                {'title': 'Sustainable Design', 'description': 'Focus on green building practices and sustainable construction methods.', 'icon': 'leaf'}
            ]
        elif 'Electronics & Communication' in course.title:
            highlights_data = [
                {'title': 'VLSI Design Training', 'description': 'Hands-on experience with chip design and semiconductor technology.', 'icon': 'microchip'},
                {'title': '5G Technology', 'description': 'Latest communication technologies and wireless system design.', 'icon': 'wifi'},
                {'title': 'Industry Labs', 'description': 'Well-equipped labs with latest test equipment and design tools.', 'icon': 'tools'},
                {'title': 'Research Opportunities', 'description': 'Access to cutting-edge research in communication and electronics.', 'icon': 'search'}
            ]
        elif 'Electrical' in course.title:
            highlights_data = [
                {'title': 'Power Systems Focus', 'description': 'Comprehensive training in power generation, transmission, and distribution.', 'icon': 'bolt'},
                {'title': 'Renewable Energy', 'description': 'Specialization in solar, wind, and other renewable energy systems.', 'icon': 'solar-panel'},
                {'title': 'Smart Grid Technology', 'description': 'Modern grid systems and electrical automation technologies.', 'icon': 'network-wired'},
                {'title': 'Industrial Training', 'description': 'Hands-on experience with industrial electrical systems and automation.', 'icon': 'industry'}
            ]
        elif 'Mechanical' in course.title:
            highlights_data = [
                {'title': 'Advanced Manufacturing', 'description': 'Training in CNC machining, 3D printing, and modern manufacturing processes.', 'icon': 'cogs'},
                {'title': 'Robotics & Automation', 'description': 'Hands-on experience with industrial robotics and automation systems.', 'icon': 'robot'},
                {'title': 'CAD/CAM Training', 'description': 'Proficiency in latest computer-aided design and manufacturing software.', 'icon': 'drafting-compass'},
                {'title': 'Automotive Focus', 'description': 'Specialization tracks in automotive engineering and electric vehicles.', 'icon': 'car'}
            ]
        else:  # General engineering highlights
            highlights_data = [
                {'title': 'Comprehensive Curriculum', 'description': 'Complete coverage of engineering fundamentals and advanced topics.', 'icon': 'book'},
                {'title': 'Practical Learning', 'description': 'Extensive laboratory work and project-based learning approach.', 'icon': 'tools'},
                {'title': 'Industry Ready', 'description': 'Curriculum designed with industry requirements and current trends.', 'icon': 'industry'},
                {'title': 'Research Focus', 'description': 'Opportunities for research and innovation in engineering applications.', 'icon': 'microscope'}
            ]
        
        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 Engineering courses!'))
