from src.utils.database import db_instance
from src.utils.file_importer import excel_importer
from src.core.random_selector import random_selector, order_selector
from src.core.animation_engine import AnimationEngine
from src.utils.helpers import get_answer_score

class DataManager:
    """数据管理中间层，协调各模块"""
    def __init__(self):
        self.db = db_instance
        self.excel = excel_importer
        self.random_selector = random_selector
        self.order_selector = order_selector
        self.anim_engine = None
        # 新增：检查数据库实例是否初始化成功
        if self.db is None:
            raise Exception("数据库连接初始化失败，请检查config/settings.json中的MySQL配置")

    def init_animation(self, label):
        """初始化动画引擎"""
        self.anim_engine = AnimationEngine(label)

    def import_excel(self, file_path):
        """导入Excel学生名单（新增：操作前重连数据库）"""
        if self.db:
            self.db.reconnect()  # 解决db4free空闲断开连接问题
        return self.excel.import_students(file_path)

    def export_excel(self, file_path=None):
        """导出积分详单（新增：操作前重连数据库）"""
        if self.db:
            self.db.reconnect()
        return self.excel.export_scores(file_path)

    def random_call(self):
        """随机点名（含动画，新增：数据库重连+空值检查）"""
        if self.db is None:
            return None, "数据库未连接，无法获取学生数据"
        self.db.reconnect()  # 重连数据库
        self.random_selector.refresh_students()
        student, msg = self.random_selector.select()
        if student and self.anim_engine:
            self.anim_engine.start_roll(student)
        return student, msg

    def order_call(self):
        """顺序点名（无动画，直接显示，优化：固定顺序不重置+空数据处理）"""
        if self.db is None:
            return None, "数据库未连接，无法获取学生数据"

        self.db.reconnect()  # 重连数据库

        # 仅在首次调用或学生列表为空时刷新数据（避免每次调用重置顺序）
        if not hasattr(self.order_selector, 'students') or len(self.order_selector.students) == 0:
            self.order_selector.refresh_students()

        # 检查学生列表是否为空
        if len(self.order_selector.students) == 0:
            return None, "没有可用的学生数据，请先导入学生名单"

        student, msg = self.order_selector.select()

        # 当所有学生点完一轮后，自动重置顺序（可选逻辑，根据需求调整）
        if "已完成一轮" in msg:
            self.order_selector.refresh_students()  # 重置为初始顺序
            msg += "，已自动重置顺序"

        return student, msg

    def record_call(self, student_id, call_mode, is_arrived, answer_level):
        """记录点名结果（新增：数据库重连+异常捕获）"""
        if self.db is None:
            return False
        self.db.reconnect()  # 重连数据库
        try:
            answer_score = get_answer_score(answer_level)
            return self.db.add_call_record(student_id, call_mode, is_arrived, answer_score)
        except Exception as e:
            print(f"记录点名结果失败：{str(e)}")
            return False

    def get_all_students(self):
        """获取所有学生（新增：数据库重连+空值检查）"""
        if self.db is None:
            return []
        self.db.reconnect()  # 重连数据库
        return self.db.get_all_students()

# 单例（新增：异常捕获，避免数据库初始化失败导致程序崩溃）
try:
    data_manager = DataManager()
except Exception as e:
    print(f"DataManager初始化失败：{e}")
    data_manager = None  # 初始化失败时设为None