"""
课程统计服务
"""
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.exam import Exam
from app.models.course import Course
from app.core.logger import get_logger

logger = get_logger(__name__)


class CourseStatisticsService:
    """课程统计服务类"""
    
    async def update_course_student_count(
        self, 
        db: AsyncSession, 
        course_id: int
    ) -> int:
        """
        更新课程学员数统计
        
        Args:
            db: 数据库会话
            course_id: 课程ID
            
        Returns:
            更新后的学员数
        """
        try:
            # 统计该课程的不同学员数（基于考试记录）
            stmt = select(func.count(func.distinct(Exam.user_id))).where(
                Exam.course_id == course_id,
                Exam.is_deleted == False
            )
            result = await db.execute(stmt)
            student_count = result.scalar_one() or 0
            
            # 更新课程表
            course_stmt = select(Course).where(
                Course.id == course_id,
                Course.is_deleted == False
            )
            course_result = await db.execute(course_stmt)
            course = course_result.scalar_one_or_none()
            
            if course:
                course.student_count = student_count
                await db.commit()
                logger.info(f"更新课程 {course_id} 学员数: {student_count}")
                return student_count
            else:
                logger.warning(f"课程 {course_id} 不存在")
                return 0
                
        except Exception as e:
            logger.error(f"更新课程学员数失败: {str(e)}", exc_info=True)
            await db.rollback()
            raise


# 创建全局实例
course_statistics_service = CourseStatisticsService()

