import random
from src.utils.database import db_instance
from src.utils.helpers import calculate_weight

class RandomSelector:
    """随机点名算法类"""
    def __init__(self):
        self.students = []
        self.refresh_students()

    def refresh_students(self):
        """刷新学生列表"""
        self.students = db_instance.get_all_students()

    def select(self) -> tuple:
        """随机选择学生（积分越高概率越低）"""
        if not self.students:
            return None, "暂无学生数据，请先导入名单"
        
        # 提取学号和积分
        student_ids = [s[0] for s in self.students]
        scores = [s[3] for s in self.students]
        # 计算权重
        weights = calculate_weight(scores)
        # 按权重随机选择
        selected_id = random.choices(student_ids, weights=weights, k=1)[0]
        # 获取选中学生详情
        selected_student = [s for s in self.students if s[0] == selected_id][0]
        return selected_student, "随机点名成功"

class OrderSelector:
    """顺序点名算法类"""
    def __init__(self):
        self.students = []
        self.index = 0
        self.refresh_students()

    def refresh_students(self):
        """刷新学生列表"""
        self.students = db_instance.get_all_students()
        self.index = 0  # 重置索引

    def select(self) -> tuple:
        """按学号顺序选择学生"""
        if not self.students:
            return None, "暂无学生数据，请先导入名单"
        
        # 循环选择
        selected_student = self.students[self.index]
        self.index = (self.index + 1) % len(self.students)
        return selected_student, "顺序点名成功"

# 单例
random_selector = RandomSelector()
order_selector = OrderSelector()