import uos
import json
import time
import uhashlib
import ubinascii  # 导入用于转换二进制到十六进制字符串的模块


class Main():
    def __init__(self):
        pass

    def get_has256_config(self):
        try:
            with open("/temp/_to_move_files_config.json", "rb") as f:
                data = f.read()
                data = data.decode("utf-8")
                data = json.loads(data)
        except:
            data = {}
        return data

    def calculate_sha256(self, path):
        h = uhashlib.sha256()
        with open(path, 'rb') as f:
            while True:
                chunk = f.read(1024)
                if not chunk:
                    break
                h.update(chunk)

        # 获取摘要并转换为十六进制字符串
        hash_bytes = h.digest()  # 获取摘要的二进制形式
        return ubinascii.hexlify(hash_bytes).decode()  # 将二进制摘要转换为十六进制字符串

    def run(self):
        """
        步骤：
        1、检查需要更新的配置文件
        2、检查文件的md5值
        3、移动文件到指定目录进行替换
        """
        config_data = self.get_has256_config()
        if not config_data:
            print("错误")
            print("config_data 为空或异常")
            return
        f = True
        for file_path, value in config_data.items():
            _has256 = self.calculate_sha256(file_path)
            if _has256 != value:
                print("文件：{} has不一致".format(file_path))
                f = False
        if not f:
            print("错误")
            return
        # ============移动文件进行替换
        for file_path in config_data:
            src_path = file_path
            dst_path = file_path.replace("/temp", "")
            self.move_file(src_path, dst_path)
        print("更新成功")

    def move_file(self, src_path, dst_path):
        """Move a file from src_path to dst_path, overwriting if the destination exists."""
        try:
            # 检查目标文件是否存在
            if self.check_exists(dst_path):
                # print(f"Destination file {dst_path} exists. Removing it...")
                uos.remove(dst_path)  # 删除目标文件以允许覆盖

            # 复制文件内容
            with open(src_path, 'rb') as src_file:
                with open(dst_path, 'wb') as dst_file:
                    while True:
                        chunk = src_file.read(1024)  # 分块读取和写入以节省内存
                        if not chunk:
                            break
                        dst_file.write(chunk)

            # print(f"File copied from {src_path} to {dst_path}.")

            # 可选：删除源文件（如果需要移动而非复制）
            uos.remove(src_path)
            # print(f"Source file {src_path} removed.")
        except OSError as e:
            print("文件移动错误")
            print("Error moving file:", e)

    def check_exists(self, path):
        """Check if a file or directory exists."""
        try:
            # 尝试获取路径的状态
            uos.stat(path)
            return True
        except OSError:
            # 如果发生OSError异常，说明路径不存在
            return False


if __name__ == '__main__':
    Main().run()
