from rest_framework import serializers
from .models import Batch, AllCourse, Chapter, Lesson, CourseEnrollment, LessonProgress
from subscriptions.serializers import ProfileSerializers

class BatchSerializer(serializers.ModelSerializer):
    trainer_name = serializers.CharField(source='trainer.name', read_only=True)
    
    class Meta:
        model = Batch
        fields = [
            'id', 'name', 'description', 'trainer', 'trainer_name',
            'start_date', 'end_date', 'schedule_time', 'max_students',
            'is_active', 'created_at', 'updated_at'
        ]

class LessonSerializer(serializers.ModelSerializer):
    is_completed = serializers.SerializerMethodField()
    progress_data = serializers.SerializerMethodField()
    
    class Meta:
        model = Lesson
        fields = [
            'id', 'title', 'description', 'lesson_type', 'video_file',
            'video_url', 'content', 'duration_minutes', 'order',
            'is_published', 'is_completed', 'progress_data', 'created_at', 'updated_at'
        ]
    
    def get_is_completed(self, obj):
        request = self.context.get('request')
        if request and hasattr(request, 'user') and request.user.is_authenticated:
            try:
                profile = request.user.profile
                enrollment = CourseEnrollment.objects.get(
                    course=obj.chapter.course,
                    student=profile,
                    is_active=True
                )
                progress = LessonProgress.objects.filter(
                    enrollment=enrollment,
                    lesson=obj
                ).first()
                return progress.is_completed if progress else False
            except CourseEnrollment.DoesNotExist:
                return False
        return False
    
    def get_progress_data(self, obj):
        request = self.context.get('request')
        if request and hasattr(request, 'user') and request.user.is_authenticated:
            try:
                profile = request.user.profile
                enrollment = CourseEnrollment.objects.get(
                    course=obj.chapter.course,
                    student=profile,
                    is_active=True
                )
                progress = LessonProgress.objects.filter(
                    enrollment=enrollment,
                    lesson=obj
                ).first()
                if progress:
                    return {
                        'time_watched': progress.time_watched,
                        'last_position': progress.last_position,
                        'completed_at': progress.completed_at
                    }
            except CourseEnrollment.DoesNotExist:
                pass
        return None

class ChapterSerializer(serializers.ModelSerializer):
    lessons = LessonSerializer(many=True, read_only=True)
    lessons_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Chapter
        fields = [
            'id', 'title', 'description', 'order', 'is_published',
            'lessons', 'lessons_count', 'created_at', 'updated_at'
        ]
    
    def get_lessons_count(self, obj):
        return obj.lessons.count()

class AllCourseSerializer(serializers.ModelSerializer):
    trainer_name = serializers.CharField(source='trainer.name', read_only=True)
    chapters = ChapterSerializer(many=True, read_only=True)
    total_chapters = serializers.SerializerMethodField()
    total_lessons = serializers.SerializerMethodField()
    enrollment_status = serializers.SerializerMethodField()
    progress_percentage = serializers.SerializerMethodField()
    
    class Meta:
        model = AllCourse
        fields = [
            'id', 'name', 'description', 'trainer', 'trainer_name',
            'price', 'course_video', 'thumbnail', 'batch', 'is_published',
            'chapters', 'total_chapters', 'total_lessons', 'enrollment_status',
            'progress_percentage', 'created_at', 'updated_at'
        ]
    
    def get_total_chapters(self, obj):
        return obj.get_total_chapters()
    
    def get_total_lessons(self, obj):
        return obj.get_total_lessons()
    
    def get_enrollment_status(self, obj):
        request = self.context.get('request')
        if request and hasattr(request, 'user') and request.user.is_authenticated:
            try:
                profile = request.user.profile
                enrollment = CourseEnrollment.objects.get(
                    course=obj,
                    student=profile,
                    is_active=True
                )
                return {
                    'is_enrolled': True,
                    'enrollment_date': enrollment.enrollment_date,
                    'is_active': enrollment.is_active
                }
            except CourseEnrollment.DoesNotExist:
                return {'is_enrolled': False}
        return {'is_enrolled': False}
    
    def get_progress_percentage(self, obj):
        request = self.context.get('request')
        if request and hasattr(request, 'user') and request.user.is_authenticated:
            try:
                profile = request.user.profile
                enrollment = CourseEnrollment.objects.get(
                    course=obj,
                    student=profile,
                    is_active=True
                )
                return enrollment.get_progress_percentage()
            except CourseEnrollment.DoesNotExist:
                return 0
        return 0

class CourseEnrollmentSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='student.name', read_only=True)
    course_name = serializers.CharField(source='course.name', read_only=True)
    progress_percentage = serializers.SerializerMethodField()
    
    class Meta:
        model = CourseEnrollment
        fields = [
            'id', 'course', 'course_name', 'student', 'student_name',
            'enrollment_date', 'is_active', 'is_deleted', 'progress_percentage',
            'created_at', 'updated_at'
        ]
    
    def get_progress_percentage(self, obj):
        return obj.get_progress_percentage()

class LessonProgressSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='enrollment.student.name', read_only=True)
    lesson_title = serializers.CharField(source='lesson.title', read_only=True)
    
    class Meta:
        model = LessonProgress
        fields = [
            'id', 'enrollment', 'lesson', 'student_name', 'lesson_title',
            'is_completed', 'completed_at', 'time_watched', 'last_position',
            'created_at', 'updated_at'
        ]

class CourseDetailSerializer(serializers.ModelSerializer):
    """Detailed serializer for course view with full structure"""
    trainer_name = serializers.CharField(source='trainer.name', read_only=True)
    batch_name = serializers.CharField(source='batch.name', read_only=True)
    chapters = ChapterSerializer(many=True, read_only=True)
    enrollment = serializers.SerializerMethodField()
    
    class Meta:
        model = AllCourse
        fields = [
            'id', 'name', 'description', 'trainer', 'trainer_name',
            'price', 'course_video', 'thumbnail', 'batch', 'batch_name',
            'is_published', 'chapters', 'enrollment', 'created_at', 'updated_at'
        ]
    
    def get_enrollment(self, obj):
        request = self.context.get('request')
        if request and hasattr(request, 'user') and request.user.is_authenticated:
            try:
                profile = request.user.profile
                enrollment = CourseEnrollment.objects.get(
                    course=obj,
                    student=profile,
                    is_active=True
                )
                return {
                    'is_enrolled': True,
                    'enrollment_date': enrollment.enrollment_date,
                    'progress_percentage': enrollment.get_progress_percentage(),
                    'total_chapters': obj.get_total_chapters(),
                    'total_lessons': obj.get_total_lessons()
                }
            except CourseEnrollment.DoesNotExist:
                return {'is_enrolled': False}
        return {'is_enrolled': False}
