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
)
from colleges.models import College

class Command(BaseCommand):
    help = 'Seeds the database with courses for Roorkee College of Business Studies'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to seed Business Studies courses'))
        
        # Get the Business Studies college
        try:
            business_college = College.objects.get(slug='roorkee-college-of-business-studies')
            self.stdout.write(self.style.SUCCESS(f'Found college: {business_college.name}'))
        except College.DoesNotExist:
            self.stdout.write(self.style.ERROR('Business Studies college not found. Please ensure the college exists.'))
            return
        
        # Create media directories if they don't exist
        os.makedirs(os.path.join(settings.MEDIA_ROOT, 'courses/banners'), exist_ok=True)
        
        # Function to download and save image
        def save_image_from_url(url, field_name):
            try:
                response = requests.get(url)
                if response.status_code == 200:
                    filename = f"{field_name}.jpg"
                    image_content = ContentFile(response.content, name=filename)
                    return image_content
                else:
                    self.stdout.write(self.style.WARNING(f"Failed to download image from {url}"))
                    return None
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"Error downloading image: {str(e)}"))
                return None
        
        # Course data based on raw-data.txt for business studies
        courses_data = [
            # Undergraduate Programs
            {
                'title': 'B.Com',
                'short_description': 'Bachelor of Commerce program providing comprehensive knowledge in accounting, finance, taxation, and business fundamentals.',
                'overview': 'The Bachelor of Commerce (B.Com) is a comprehensive undergraduate program designed to provide students with a strong foundation in commerce, accounting, finance, economics, and business management. The curriculum covers areas such as financial accounting, cost accounting, taxation, business law, economics, and statistics. Students will develop analytical and problem-solving skills essential for careers in accounting, finance, banking, and business management.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Commerce & Finance'
            },
            {
                'title': 'BBA',
                'short_description': 'Bachelor of Business Administration focusing on management principles, leadership skills, and business strategy.',
                'overview': 'The Bachelor of Business Administration (BBA) program is designed to develop future business leaders with comprehensive knowledge of management principles, organizational behavior, marketing, finance, and strategic planning. Students will learn about business operations, entrepreneurship, project management, and leadership skills through case studies, internships, and practical projects. The program prepares graduates for management roles in various industries.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Business Administration'
            },
            {
                'title': 'Bachelors in Hotel Management',
                'short_description': 'Comprehensive program in hospitality management covering hotel operations, food service, and tourism industry.',
                'overview': 'The Bachelor in Hotel Management program provides comprehensive training in hospitality industry operations, including hotel management, food and beverage service, housekeeping, front office operations, and hospitality marketing. Students will gain practical experience through industry internships and learn about customer service excellence, revenue management, and hospitality technology. The program prepares graduates for management roles in hotels, resorts, restaurants, and tourism companies.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Hospitality Management'
            },
            {
                'title': 'Bachelors in Hospital Administration',
                'short_description': 'Specialized program in healthcare management focusing on hospital operations and healthcare systems.',
                'overview': 'The Bachelor in Hospital Administration program combines healthcare knowledge with management principles to prepare professionals for administrative roles in healthcare organizations. Students will learn about healthcare systems, hospital operations, medical record management, healthcare finance, quality assurance, and healthcare laws. The program includes practical training in hospitals and healthcare facilities to provide real-world experience.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Healthcare Management'
            },
            {
                'title': 'BA English',
                'short_description': 'Bachelor of Arts in English focusing on literature, language skills, and communication excellence.',
                'overview': 'The Bachelor of Arts in English program provides comprehensive study of English literature, language, linguistics, and communication skills. Students will explore classical and contemporary literature, develop critical thinking and analytical skills, and enhance their written and oral communication abilities. The program prepares graduates for careers in education, journalism, content writing, publishing, and corporate communication.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Liberal Arts'
            },
            {
                'title': 'BA Economics',
                'short_description': 'Bachelor of Arts in Economics covering microeconomics, macroeconomics, and economic policy analysis.',
                'overview': 'The Bachelor of Arts in Economics program provides comprehensive understanding of economic principles, theories, and their practical applications. Students will study microeconomics, macroeconomics, econometrics, international economics, and economic policy. The curriculum emphasizes analytical thinking, quantitative methods, and economic research. Graduates are prepared for careers in banking, government, research organizations, and corporate planning.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Economics'
            },
            {
                'title': 'BA Tourism & Management',
                'short_description': 'Comprehensive program combining tourism industry knowledge with management principles.',
                'overview': 'The Bachelor of Arts in Tourism & Management program provides specialized knowledge of the tourism industry combined with management principles. Students will learn about tourism planning, destination management, travel operations, tourism marketing, and sustainable tourism practices. The program includes practical training through industry internships and prepares graduates for careers in travel agencies, tour operators, hotels, and tourism boards.',
                'duration': '3 Years (6 Semesters)',
                'category': 'Tourism Management'
            },
            
            # Postgraduate Programs
            {
                'title': 'MBA Global',
                'short_description': 'Global MBA program with international business focus and cross-cultural management expertise.',
                'overview': 'The MBA Global program is designed for professionals seeking to develop international business expertise and global leadership skills. The curriculum covers international finance, global marketing, cross-cultural management, international trade, and global supply chain management. Students will gain exposure to global business practices through case studies, international projects, and industry interactions. The program prepares graduates for senior management roles in multinational corporations.',
                'duration': '2 Years (4 Semesters)',
                'category': 'International Business'
            },
            {
                'title': 'MBA in Pharma Management',
                'short_description': 'Specialized MBA focusing on pharmaceutical industry management and healthcare business.',
                'overview': 'The MBA in Pharma Management is a specialized program designed for the pharmaceutical and healthcare industry. Students will learn about pharmaceutical marketing, regulatory affairs, drug development processes, healthcare policy, and pharma supply chain management. The curriculum combines business management principles with industry-specific knowledge. Graduates are prepared for management roles in pharmaceutical companies, healthcare organizations, and regulatory bodies.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Pharmaceutical Management'
            },
            {
                'title': 'MBA Executive',
                'short_description': 'Executive MBA program for working professionals with focus on strategic leadership and management.',
                'overview': 'The MBA Executive program is designed for experienced working professionals who want to advance their careers while continuing their professional responsibilities. The curriculum focuses on strategic management, leadership development, organizational transformation, and advanced business analytics. Classes are scheduled to accommodate working professionals, and the program emphasizes practical application of concepts to real-world business challenges.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Executive Management'
            },
            {
                'title': 'MBA (with IIM Certification) (Finance/HR/Marketing)',
                'short_description': 'MBA program with IIM certification offering specializations in Finance, HR, and Marketing.',
                'overview': 'The MBA program with IIM Certification offers specialized tracks in Finance, Human Resources, and Marketing. This prestigious program combines rigorous academic curriculum with industry best practices. Students will benefit from IIM faculty expertise, advanced case study methodology, and industry mentorship. The program includes specialization-specific projects, internships, and certification from Indian Institute of Management, preparing graduates for leadership roles in their chosen specialization.',
                'duration': '2 Years (4 Semesters)',
                'category': 'Management with IIM Certification'
            }
        ]
        
        # 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 = [
                'business,office,professional', 'finance,accounting,money', 
                'management,leadership,strategy', 'hospitality,hotel,service',
                'healthcare,hospital,medical', 'tourism,travel,destination',
                'economics,market,analysis'
            ]
            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 'MBA' in course.title:
            academic_qual = "Bachelor's degree in any discipline from a recognized university."
            if 'Executive' in course.title:
                minimum_marks = "Minimum 50% aggregate with 3+ years work experience (45% for SC/ST/OBC)."
                entrance_exam = "CAT/MAT/XAT/CMAT or University Entrance Test with personal interview."
            else:
                minimum_marks = "Minimum 50% aggregate in graduation (45% for SC/ST/OBC)."
                entrance_exam = "CAT/MAT/XAT/CMAT or University Entrance Test with group discussion and personal interview."
        elif 'BA' in course.title or 'B.Com' in course.title or 'BBA' in course.title or 'Bachelor' in course.title:
            academic_qual = "10+2 (Senior Secondary) from a recognized board in any stream."
            minimum_marks = "Minimum 50% aggregate in 10+2 (45% for SC/ST/OBC)."
            entrance_exam = "Merit-based admission or university entrance test."
        else:
            academic_qual = "10+2 (Senior Secondary) from a recognized board."
            minimum_marks = "Minimum 50% aggregate in 10+2 (45% for SC/ST/OBC)."
            entrance_exam = "Merit-based admission or entrance examination."
        
        CourseEligibility.objects.update_or_create(
            course=course,
            defaults={
                'academic_qualification': academic_qual,
                'minimum_marks': minimum_marks,
                'entrance_exam': entrance_exam
            }
        )
    
    def _create_course_fees(self, course, course_data):
        """Create fee structure for the course"""
        # Base fees based on course type
        if 'MBA' in course.title:
            if 'IIM Certification' in course.title:
                domestic_fee = "₹3,50,000 per year"
                international_fee = "$12,000 per year"
            elif 'Executive' in course.title:
                domestic_fee = "₹2,80,000 per year"
                international_fee = "$10,000 per year"
            else:
                domestic_fee = "₹2,20,000 per year"
                international_fee = "$8,000 per year"
        elif 'Hospital Administration' in course.title or 'Hotel Management' in course.title:
            domestic_fee = "₹1,40,000 per year"
            international_fee = "$5,000 per year"
        elif 'BBA' in course.title:
            domestic_fee = "₹1,20,000 per year"
            international_fee = "$4,500 per year"
        else:  # BA and B.Com courses
            domestic_fee = "₹90,000 per year"
            international_fee = "$3,500 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 'MBA' in course.title:
            if 'IIM Certification' in course.title:
                highlights_data = [
                    {'title': 'IIM Certification', 'description': 'Prestigious certification from Indian Institute of Management.', 'icon': 'certificate'},
                    {'title': 'Specialization Tracks', 'description': 'Choose from Finance, HR, or Marketing specializations.', 'icon': 'route'},
                    {'title': 'Industry Mentorship', 'description': 'Direct mentorship from industry leaders and IIM faculty.', 'icon': 'user-tie'},
                    {'title': 'Case Study Method', 'description': 'Advanced case study methodology and real business scenarios.', 'icon': 'briefcase'}
                ]
            elif 'Executive' in course.title:
                highlights_data = [
                    {'title': 'Working Professional Focus', 'description': 'Designed for experienced professionals without career break.', 'icon': 'user-clock'},
                    {'title': 'Weekend Classes', 'description': 'Flexible schedule with weekend and evening classes.', 'icon': 'calendar'},
                    {'title': 'Leadership Development', 'description': 'Focus on strategic leadership and organizational transformation.', 'icon': 'users'},
                    {'title': 'Networking Opportunities', 'description': 'Connect with senior professionals across industries.', 'icon': 'handshake'}
                ]
            else:
                highlights_data = [
                    {'title': 'Global Perspective', 'description': 'International business focus with global case studies.', 'icon': 'globe'},
                    {'title': 'Industry Projects', 'description': 'Real-world projects with leading companies.', 'icon': 'project-diagram'},
                    {'title': 'Placement Support', 'description': '100% placement assistance with top recruiters.', 'icon': 'briefcase'},
                    {'title': 'Specialization Options', 'description': 'Multiple specialization tracks available.', 'icon': 'graduation-cap'}
                ]
        elif 'Hotel Management' in course.title:
            highlights_data = [
                {'title': 'Industry Training', 'description': 'Extensive practical training in 5-star hotels and resorts.', 'icon': 'hotel'},
                {'title': 'Global Exposure', 'description': 'International internship and exchange programs.', 'icon': 'plane'},
                {'title': 'Professional Skills', 'description': 'Hands-on training in all aspects of hotel operations.', 'icon': 'tools'},
                {'title': 'Industry Connections', 'description': 'Strong network with leading hospitality brands.', 'icon': 'network-wired'}
            ]
        elif 'Hospital Administration' in course.title:
            highlights_data = [
                {'title': 'Healthcare Focus', 'description': 'Specialized training in healthcare management and administration.', 'icon': 'hospital'},
                {'title': 'Medical Knowledge', 'description': 'Understanding of medical processes and healthcare systems.', 'icon': 'stethoscope'},
                {'title': 'Hospital Internships', 'description': 'Practical training in leading hospitals and healthcare facilities.', 'icon': 'user-md'},
                {'title': 'Career Growth', 'description': 'High demand for healthcare administrators in growing industry.', 'icon': 'chart-line'}
            ]
        elif 'Tourism' in course.title:
            highlights_data = [
                {'title': 'Tourism Industry Focus', 'description': 'Comprehensive understanding of travel and tourism operations.', 'icon': 'map-marked'},
                {'title': 'Destination Management', 'description': 'Learn about tourism planning and destination development.', 'icon': 'map'},
                {'title': 'Practical Training', 'description': 'Internships with travel agencies and tour operators.', 'icon': 'suitcase'},
                {'title': 'Cultural Awareness', 'description': 'Understanding of diverse cultures and sustainable tourism.', 'icon': 'globe-asia'}
            ]
        else:  # General business courses
            highlights_data = [
                {'title': 'Strong Foundation', 'description': 'Comprehensive foundation in business and commerce principles.', 'icon': 'building'},
                {'title': 'Practical Learning', 'description': 'Case studies, projects, and industry interactions.', 'icon': 'book-open'},
                {'title': 'Career Flexibility', 'description': 'Multiple career paths in business, finance, and management.', 'icon': 'route'},
                {'title': 'Industry Ready', 'description': 'Curriculum designed to meet current industry requirements.', 'icon': 'briefcase'}
            ]
        
        for highlight_data in highlights_data:
            CourseHighlight.objects.update_or_create(
                course=course,
                title=highlight_data['title'],
                defaults={
                    'description': highlight_data['description'],
                    'icon': highlight_data['icon']
                }
            )
        
        self.stdout.write(self.style.SUCCESS('Successfully seeded all Business Studies courses!'))
