import json
import random
from datetime import datetime

# 读取配置
with open("config/settings.json", "r", encoding="utf-8") as f:
    CONFIG = json.load(f)
SCORE_RULES = CONFIG["score_rules"]
VIS_CONFIG = CONFIG["visualization"]

def format_time(timestamp: datetime = None) -> str:
    """格式化时间为字符串"""
    if not timestamp:
        timestamp = datetime.now()
    return timestamp.strftime("%Y-%m-%d %H:%M:%S")

def calculate_weight(scores: list) -> list:
    """计算随机点名权重：积分越高，权重越低"""
    weights = []
    for score in scores:
        if score >= 0:
            # 正积分：权重=1/(积分+1)，避免除以0
            weight = 1 / (score + 1)
        else:
            # 负积分：权重=绝对值+1，提高被点到概率
            weight = abs(score) + 1
        weights.append(weight)
    return weights

def get_answer_score(level: str) -> float:
    """根据回答等级返回分数（简易版，可扩展）"""
    level_map = {
        "优秀": 3.0,
        "良好": 2.0,
        "及格": 0.5,
        "错误": -1.0,
        "重复正确": SCORE_RULES["repeat_correct"],
        "重复错误": SCORE_RULES["repeat_wrong"]
    }
    return level_map.get(level, 0.0)

def get_visual_top_n(students: list) -> list:
    """获取可视化的TOP N学生"""
    # 按积分降序排序，取前N个
    sorted_students = sorted(students, key=lambda x: x[3], reverse=True)
    return sorted_students[:VIS_CONFIG["top_n"]]