
import lupa
from lupa import LuaRuntime
import execjs
import json
import datetime
from datetime import datetime, timedelta




def lua_test(lua_file:str,json_file:str,data:bytearray):
    # 初始化lua运行环境
    lua = LuaRuntime(unpack_returned_tuples=True)
    # 初始化全局变量 json
    save_json=lua.eval("function(a) json=a end")
    with open("file/json.lua",encoding="utf-8") as f:
        save_json(lua.execute(f.read()))
    # 初始化全局变量 prints
    save_prints=lua.eval("function(a) prints=a end")
    with open("file/prints.lua",encoding="utf-8") as f:
        save_prints(lua.execute(f.read()))
    
    # 初始化全局变量 cfg_name
    # lua.execute("cfg_name=\""+json_file+"\"\n")

    # 初始化配置字符串
    save_cfg_str=lua.eval("function(a) check_cfg_str=a end")
    with open(json_file,encoding="utf-8") as f:
        a=f.read()
        save_cfg_str(a)
    
    # 初始化全局变量 check_data
    s=data.hex(' ')
    # print("输入数据",s)
    s=s.replace(" ",",0x")
    s="0x"+s
    lua.execute("check_data={"+s+"}\n")
    # 执行判定脚本
    with open(lua_file,encoding="utf-8") as f:
        lua.execute(f.read())
        a,b=lua.globals().main()
        return a,b
    return "脚本执行失败",0xd1




class save:
    def __init__(self,scheme:str,script:str) -> None:
        self.scheme=scheme
        self.script=script
        self.save_file=scheme.split(".")[0]+".csv"
        print("save file:",self.save_file)
        with open(scheme,"rb") as f:
            self.json_obj=json.loads(f.read())

        # 计算返回参数个数
    def calc_retnum(self):
        num=0
        for i in self.json_obj["TaskArray"]:
            num=num+i["ReturnCount"]
        # print("checkret_num=",num)
        return num
        # 计算超限错误字节个数
    def calc_parerrnum(self):
        return (self.calc_retnum()+7)//8

        # 调用这个函数保存数据
    def save(self,data:bytearray):
        d=data[1:]
        ret_num=self.calc_retnum()*2+8+self.calc_parerrnum()
        slave_num=len(d)//ret_num
        for i in range(slave_num):
            # print("slave:",i+1)
            self.save_item(i+1,d[i*ret_num:i*ret_num+ret_num])

    # 保存一个条目
    def save_item(self,slave_addr:int,d:bytearray):
        # print("save_item",d.hex(" "))
        errnum=self.calc_parerrnum()
        s=str(slave_addr)+','
        s+='=\"'+d[0:8].hex()+'\"'+','
        s+='=\"'+self.hex2bit(d[8:8+errnum])+'\"'+','
        s+=self.hex2int(d[8+errnum:])
        # print(d[8:8+errnum].hex(' '))
        a,b=lua_test(self.script,self.scheme,d)
        s=s+a+','+str(b)
        # print(s)
        with open(self.save_file,"+a") as f:
            f.write(s+'\n')

    # 把两个字节拼为一个int
    def hex2int(self,d:bytearray):
        s=""
        for i in range(len(d)//2):
            s+=str(d[i*2]|(d[i*2+1]<<8))+','
        return s
    
    # 把数据转换为二进制字符串
    def hex2bit(self,d:bytearray):
        s=""
        for i in range(len(d)*8):
            if(d[i//8]&(1<<(i%8))!=0):
                s+='1'
            else:
                s+='0'
            if((i>0) and ((i+1)%8==0) and ((i+1)<len(d)*8)):
                s+='_'
        return s








def js_test():
    with open("file/judge.js",encoding="utf-8") as f:
        context1 = execjs.compile(f.read())
        json=open("file/checker_ye_cfg.json",encoding="utf-8").read()
        check_data=bytearray([0xB5,0x96,0xEC,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0x01,0x00,0x00,0x00,0x00,0x21,0x00,0x12,0x01,0x00,0x00,0x00,0x00,0xB5,0x00,0xB1,0x00,0x6B,0x00,0x00,0x00,0xA5,0x02,0xA4,0x02,0x00,0x00,0xA4,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00])
        a=context1.call("main",1,check_data)
        print(a)


if __name__ == "__main__":
    # sa=save()
    # print(sa.hex2bit(bytes([0xab,0xcd])))
    # js_test()
    check_data=bytearray([0x00,0x08,0x00,0x02,0x50,0x01,0x00,0x00,0x40,0x00,0x46,0xe3,0x4f,0x03,0x58,0x00,0xb5,0x00,0x00,0x01,0x09,0x01,0x10,0x00,0x00,0x00,0x4b,0x00,0x78,0x00,0x57,0x0a,0x21,0x01,0x6a,0x00,0xec,0x00,0x04,0x01,0x4a,0x01,0x1b,0x01,0x23,0x01,0x40,0x9c,0x7e,0x06,0x90,0x00,0x43,0x00,0x77,0x00,0x00,0x00,0x03,0x00,0x40,0x9c,0x80,0x06,0x1f,0x00,0x54,0x07,0x21,0x01,0xd0,0x07,0xff,0xff])
    lua_test("file/judge-xt-checker.lua","file/7.15.json".encode("gbk").decode("utf-8"),check_data)
    # lua_test("file/judge-xt.lua","file/checker_ye_cfg.json",check_data)

