import os,re,time,json,sys

"""
模板文件目录下 题目清单.txt 文件不能缺失
"""

"""---设置是否在学生版中提供答案---"""
answered = False

"""---设置文件保存路径---"""
#目录和文件的分隔务必用/
directory = "临时文件/"
# filename = "高三二模前易错题"
filename = "新高一例题习题材料"
"""---设置文件名结束---"""

"""---设置题目列表---"""
#字典字段为文件名, 之后为内容的题号
problems_dict = {
"空中课堂必修第一册例题与习题": "011739:011987",
"新教材必修第一册课堂练习": "009426:009538",
"新教材必修第一册习题": "010017:010202",
"2025届高一校本作业必修第一章": "020001:020096,030001",
"2025届高一校本作业必修第二章": "020097:020351",
"2025届高一校本作业必修第三章": "020352:020403",
"2025届高一校本作业必修第四章": "020404:020497",
"2025届高一校本作业必修第五章": "020498:020683",
"2025届高一校本作业选择性必修第四章": "020684:020849"
}

# problems_dict =  {

# "2025届高一下学期校本作业":"21441:22047",
# "2024届高二下学期周末卷01":"40001:40017",
# "2025届高一下学期周末卷01":"40018:40036",
# "2024届高二下学期周末卷02":"40037:40056",
# "2025届高一下学期周末卷02":"40057:40082",
# "2025届高一下学期周末卷03":"40083:40104",
# "2025届高一下学期周末卷03小测":"40105:40112",
# "2025届高一下学期周末卷04旧版":"40113:40130",
# "2025届高一下学期周末卷04小测":"40131:40139",
# "2024届高二下学期周末卷03":"40140:40160",
# "2024届高二上学期期末考试":"31267:31287",
# "2025届高一上学期期末考试":"31288:31308",
# "2024届高二下学期周末卷04":"40161:40180",
# "2025届高一下学期周末卷04":"40181:40201",
# "2024届高二下学期周末卷05":"40202:40225",
# "2025届高一下学期周末卷05":"40226:40245",
# "2024届空间向量校本作业":"22048:22083",
# "2024届二项式定理校本作业":"22084:22105",
# "2025届高一下学期周末卷05小测":"40246:40255",
# "2025届高一下学期周末卷06":"40256:40273",
# "2025届高一下学期周末卷06小测":"40274:40282",
# "2025届高一下学期期中复习一(集合逻辑不等式)":"40283:40298",
# "2024届高二下学期周末卷06":"40299:40316",
# "2024届高二下学期周末卷07":"40317:40335",
# "2025届高一下学期测验01":"40336:40349",
# "2025届高一下学期测验02":"40350:40367",
# "2025届高一下学期期中复习二(幂指对函数)":"40368:40386",
# "2025届高一下学期周末卷02小测":"40387:40395",
# "2025届高一下学期周末卷07":"40396:40413",
# "2025届高一下学期周末卷07小测":"40414:40421",
# "2025届高一下学期周末卷08":"40527:40551",
# "2024届高二下学期周末卷08":"40570:40587",
# "2024届高二下学期周末卷09":"40588:40604"

# }

"""---设置题目列表结束---"""


if directory[-1] != "/":
    directory += "/"


#生成数码列表, 逗号分隔每个区块, 区块内部用:表示整数闭区间
def generate_number_set(string,dict):
    string = re.sub(r"[\n\s]","",string)
    string_list = string.split(",")
    numbers_list = []
    for s in string_list:
        if not ":" in s:
            numbers_list.append(s.zfill(6))
        else:
            start,end = s.split(":")
            for ind in range(int(start),int(end)+1):
                numbers_list.append(str(ind).zfill(6))
    return numbers_list

#将正确率转化为含颜色代码的字符串
def get_color(value):
    value = float(value)
    if value>=0.5:
        (r,g,b)=(1,2-2*value,0)
    else:
        (r,g,b)=(2*value,1,0)
    return "{" + "%.3f" %(r) + "," + "%.3f" %(g) + ",0}"


def color_value(matchobj):
    value = matchobj.group(1)
    return "\t"+"\\fcolorbox[rgb]{0,0,0}"+ get_color(value) +"{" + value +"}"


#读取题库json文件并转化为字典
with open(r"../题库0.3/Problems.json","r",encoding = "utf8") as f:
    database = f.read()
pro_dict = json.loads(database)

#读取目标数据库json并转化为字典
with open(r"../题库0.3/LessonObj.json","r",encoding = "utf8") as f:
    database = f.read()
obj_dict = json.loads(database)

try:
    os.mkdir(directory)
except:
    pass

#读取系统日期
current_time = time.localtime()
time_string = "_"+str(current_time.tm_year).zfill(4)+str(current_time.tm_mon).zfill(2)+str(current_time.tm_mday).zfill(2)


data_teachers = ""
data_students = ""

teachers_latex_file = directory + filename + "_教师用" + time_string + ".tex"
students_latex_file = directory + filename + "_学生用" + time_string + ".tex"

for section_name in problems_dict:
    problems = problems_dict[section_name]

    data_teachers += r"\newpage" + "\n\n" + r"\section{" + section_name +"}\n\n"
    data_teachers += r"\setcounter{enumi}{0}"+"\n\n"
    data_students += r"\newpage" + "\n\n" + r"\section{" + section_name +"}\n\n"
    data_students += r"\setcounter{enumi}{0}"+"\n\n"

    #生成题目列表
    problem_list = [id for id in generate_number_set(problems.strip(),pro_dict) if id in pro_dict]




    #生成教师题目字符串与学生题目字符串, 准备替换至latex文件
    for id in problem_list:
        problemset = pro_dict[id]
        problem = problemset["content"]
        solution = (problemset["solution"] if problemset["solution"] != "" else "暂无解答与提示")
        answer = "\\textcolor{red}{" + (problemset["ans"] if problemset["ans"] != "" else "暂无答案") + "}"
        remarks = (problemset["remark"] if problemset["remark"] != "" else "暂无备注")
        usages_list = problemset["usages"]
        if len(usages_list) > 0:
            usage = re.sub("\\t([\d]\.[\d]{0,10})",color_value,"\n\n".join(usages_list))
            usage = re.sub("[\\t ]([\d]\.[\d]{0,10})",color_value,usage)
        else:
            usage = "暂无使用记录"
        origin = (problemset["origin"] if problemset["origin"] != "" else "出处不详")
        objects = problemset["objs"]
        if len(objects) == 0:
            objects = "暂未关联目标\n\n"
        elif "KNONE" in [o.upper() for o in objects]:
            objects = "该题的考查目标不在目前的集合中\n\n"
        else:
            objects_string = ""
            for obj in objects:
                if not obj in obj_dict:
                    objects_string = "目标" + obj + "有误\n\n"
                    break
                else:
                    objects_string += "\\textcolor{blue}{" + obj + "|" + obj_dict[obj]["content"] + "}\n\n"
            objects = objects_string
        space = ("" if problemset["space"] == "" or answered else r"\vspace*{"+problemset["space"]+"}\n")
        tags = ("|".join(problemset["tags"]) if len(problemset["origin"])>0 else "暂无标签")
        raw_string = "\\item " + "{\\tiny ("+id+")} "+problem
        teachers_string = raw_string.replace("\\tiny","")+"\n\n关联目标:\n\n"+ objects + "\n\n标签: " + tags + "\n\n答案: "+answer + "\n\n" + "解答或提示: " + solution + "\n\n使用记录:\n\n"+ usage + "\n" + "\n\n出处: "+origin + "\n\n"
        students_string = raw_string + space + "\n\n"
        if answered:
            students_string += "答案: \\textcolor{red}{"+answer + "}\n\n"
        data_teachers += teachers_string
        data_students += students_string

#去除第一个newpage
data_teachers = data_teachers[10:]
data_students = data_students[10:]

#替换latex文件的内容并编译
with open("模板文件/题目清单.txt","r",encoding = "utf8") as f:
    latex_raw = f.read()
#识别操作系统
if sys.platform != "win32":
    latex_raw = re.sub(r"fontset[\s]*=[\s]*none","fontset = fandol",latex_raw)
    latex_raw = re.sub(r"\\setCJKmainfont",r"% \\setCJKmainfont",latex_raw)
latex_teachers = latex_raw.replace("编译模板",data_teachers)
with open(teachers_latex_file,"w",encoding = "utf8") as f:
    f.write(latex_teachers)
print("开始编译教师版本pdf文件: ", teachers_latex_file)
os.system("xelatex -interaction=batchmode -output-directory=" + directory + " "+ teachers_latex_file)
print(os.system("xelatex -interaction=batchmode -output-directory=" + directory + " "+ teachers_latex_file))

latex_students = latex_raw.replace("编译模板",data_students)
with open(students_latex_file,"w",encoding = "utf8") as f:
    f.write(latex_students)
print("开始编译学生版本pdf文件: ", students_latex_file)
os.system("xelatex -interaction=batchmode -output-directory=" + directory + " "+ students_latex_file)
print(os.system("xelatex -interaction=batchmode -output-directory=" + directory + " "+ students_latex_file))
