import json
from django.core.management.base import BaseCommand
from django.conf import settings
from courses.models import (
    Course, CourseEligibility, CourseFee, FeeDetail, HostelFee,
    Semester, Subject, CareerProspect, Recruiter, CourseHighlight,
    Testimonial, WhyJoin
)
from colleges.models import College

class Command(BaseCommand):
    help = 'Insert or update course data using the API. Default: inserts MCA course.'

    def add_arguments(self, parser):
        parser.add_argument('--slug', type=str, default='mca', help='Course slug to insert or update')
        parser.add_argument('--data_file', type=str, help='Path to JSON file with course data (overrides default)')

    def handle(self, *args, **options):
        slug = options['slug']
        data_file = options.get('data_file')

        if data_file:
            with open(data_file, 'r') as f:
                course_data = json.load(f)
        else:
            course_data = MCA_COURSE_DATA

        try:
            # Check if course exists
            try:
                course = Course.objects.get(slug=slug)
                self.stdout.write(self.style.WARNING(f"Course with slug '{slug}' already exists. Updating..."))
                update_existing = True
            except Course.DoesNotExist:
                self.stdout.write(self.style.SUCCESS(f"Creating new course with slug '{slug}'..."))
                update_existing = False

            # Get or create college
            try:
                college = College.objects.get(id=course_data.get('college_id', 1))
            except College.DoesNotExist:
                college = College.objects.first()  # Use first available college
                if not college:
                    self.stdout.write(self.style.ERROR("No college found in database. Please create a college first."))
                    return

            # Create or update course
            if update_existing:
                course.title = course_data['title']
                course.short_description = course_data['short_description']
                course.overview = course_data['overview']
                course.duration = course_data['duration']
                course.category = course_data['category']
                course.save()
            else:
                course = Course.objects.create(
                    title=course_data['title'],
                    slug=course_data['slug'],
                    short_description=course_data['short_description'],
                    overview=course_data['overview'],
                    duration=course_data['duration'],
                    category=course_data['category']
                )

            # Create eligibility
            if 'eligibility' in course_data:
                CourseEligibility.objects.filter(course=course).delete()
                CourseEligibility.objects.create(
                    course=course,
                    academic_qualification=course_data['eligibility']['academic_qualification'],
                    minimum_marks=course_data['eligibility']['minimum_marks'],
                    entrance_exam=course_data['eligibility']['entrance_exam']
                )

            # Create fees
            if 'fees' in course_data:
                CourseFee.objects.filter(course=course).delete()
                course_fee = CourseFee.objects.create(
                    course=course,
                    domestic=course_data['fees'].get('domestic', ''),
                    international=course_data['fees'].get('international', '')
                )
                
                # Create fee details
                for detail in course_data['fees'].get('details', []):
                    FeeDetail.objects.create(
                        course_fee=course_fee,
                        fee_head=detail['fee_head'],
                        first_year=detail['first_year'],
                        second_year=detail['second_year'],
                        third_year=detail['third_year'],
                        fourth_year=detail['fourth_year'],
                        is_one_time=detail['is_one_time']
                    )

            # Create hostel fee
            if 'hostel_fee' in course_data:
                HostelFee.objects.filter(course=course).delete()
                HostelFee.objects.create(
                    course=course,
                    fee_per_year=course_data['hostel_fee']['fee_per_year'],
                    ac_room_additional=course_data['hostel_fee'].get('ac_room_additional', ''),
                    security_deposit=course_data['hostel_fee'].get('security_deposit', ''),
                    notes=course_data['hostel_fee'].get('notes', '')
                )

            # Create semesters and subjects
            if 'semesters' in course_data:
                Semester.objects.filter(course=course).delete()
                for sem_data in course_data['semesters']:
                    semester = Semester.objects.create(
                        course=course,
                        name=sem_data['name'],
                        number=sem_data['number']
                    )
                    
                    for subject_data in sem_data.get('subjects', []):
                        Subject.objects.create(
                            semester=semester,
                            code=subject_data['code'],
                            name=subject_data['name'],
                            credits=subject_data['credits'],
                            description=subject_data['description']
                        )

            # Create career prospects
            if 'career_prospects' in course_data:
                CareerProspect.objects.filter(course=course).delete()
                for prospect in course_data['career_prospects']:
                    CareerProspect.objects.create(
                        course=course,
                        title=prospect['title'],
                        salary_range=prospect.get('salary_range', ''),
                        description=prospect.get('description', '')
                    )

            # Create highlights
            if 'highlights' in course_data:
                CourseHighlight.objects.filter(course=course).delete()
                for highlight in course_data['highlights']:
                    CourseHighlight.objects.create(
                        course=course,
                        title=highlight['title'],
                        description=highlight['description'],
                        icon=highlight.get('icon', '')
                    )

            # Create testimonials
            if 'testimonials' in course_data:
                Testimonial.objects.filter(course=course).delete()
                for testimonial in course_data['testimonials']:
                    Testimonial.objects.create(
                        course=course,
                        name=testimonial['name'],
                        position=testimonial['position'],
                        company=testimonial['company'],
                        content=testimonial['content']
                    )

            # Create why join
            if 'why_join' in course_data:
                WhyJoin.objects.filter(course=course).delete()
                for why in course_data['why_join']:
                    WhyJoin.objects.create(
                        course=course,
                        title=why['title'],
                        description=why['description']
                    )

            action = "updated" if update_existing else "created"
            self.stdout.write(self.style.SUCCESS(f"Course '{slug}' {action} successfully in database."))

        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Failed to insert/update course: {str(e)}"))
            import traceback
            self.stdout.write(self.style.ERROR(traceback.format_exc()))
