
import os
import ast
import sys
import time

def is_file_complete(file_path, timeout=60):
    """
    检查文件是否完全复制完成。

    :param file_path: 文件路径。
    :param timeout: 最大等待时间（秒）。
    :return: 如果文件复制完成则返回 True，否则返回 False。
    """
    if not os.path.exists(file_path):
        return False

    initial_size = os.path.getsize(file_path)
    time.sleep(1)  # 等待1秒钟，给文件写入一些时间
    final_size = os.path.getsize(file_path)

    # 如果文件大小没有变化，认为文件已复制完成
    if initial_size == final_size:
        return True

    # 如果文件大小仍在变化，则继续等待
    start_time = time.time()
    while time.time() - start_time < timeout:
        time.sleep(1)
        new_size = os.path.getsize(file_path)
        if new_size == final_size:
            return True
        final_size = new_size

    # 超过最大等待时间后认为文件未复制完成
    return False


def get_current_file_path():
    """
    获取当前文件的路径，支持打包后的程序和非打包情况。

    :return: 当前文件的路径。
    """
    # 检查是否是打包后的程序
    if getattr(sys, 'frozen', False):
        # PyInstaller 打包后的路径
        current_path = os.path.abspath(sys.argv[0])
    else:
        # 非打包情况下的路径
        current_path = os.path.abspath(__file__)
    return current_path


def save_list_to_txt(txt_path, data_list):
    """
    将 list 存入 txt 文件，每个元素占一行。如果文件不存在则新建，存在则追加。

    :param txt_path: 保存的txt路径。
    :param data_list: 待保存的数据列表。
    """
    os.makedirs(os.path.dirname(txt_path), exist_ok=True)
    mode = "a" if os.path.exists(txt_path) else "w"

    with open(txt_path, mode, encoding="utf-8") as f:
        for item in data_list:
            f.write(str(item) + "\n")


def read_list_from_txt(txt_path, parse=False):
    """从 txt 文件读取 list，可选解析数据结构

    :param txt_path: 读取的txt路径。
    :param parse: 是否解析数据，默认False。
    """
    with open(txt_path, "r", encoding="utf-8") as f:
        lines = [line.strip() for line in f.readlines()]
        return [ast.literal_eval(line) for line in lines] if parse else lines
