import datetime
import os

def save_log(filename, log_content):
    """
    保存日志到指定文件

    :param filename: 日志文件名
    :param log_content: 需要保存的日志内容
    """
    # 定义日志文件夹路径
    log_dir = "logs"
    # 检查log文件夹是否存在，不存在则创建
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 构建完整的文件路径
    file_path = os.path.join(log_dir, filename)
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 以追加模式打开文件，如果文件不存在会自动创建
    with open(file_path+".txt", 'a', encoding='utf-8') as file:
        file.write(f"[{current_time}] {log_content}\n")

def cookie_dict_to_string(cookie_dict):
    """
    将字典格式的cookie转换为字符串格式(key=value; key=value)

    Args:
        cookie_dict (dict): cookie字典

    Returns:
        str: 字符串格式的cookie
    """
    if not isinstance(cookie_dict, dict):
        raise ValueError("输入必须是字典类型")

    cookie_items = []
    for key, value in cookie_dict.items():
        cookie_items.append(f"{key}={value}")

    return "; ".join(cookie_items)
def cookie_string_to_dict(cookie_string):
    """
    将字符串格式的cookie转换为字典格式

    Args:
        cookie_string (str): 字符串格式的cookie (key=value; key=value)

    Returns:
        dict: cookie字典
    """
    if not isinstance(cookie_string, str):
        raise ValueError("输入必须是字符串类型")

    cookie_dict = {}
    if not cookie_string.strip():
        return cookie_dict

    # 按分号分割cookie项
    items = cookie_string.split(";")
    for item in items:
        item = item.strip()  # 去除前后空格
        if "=" in item:
            key, value = item.split("=", 1)  # 只分割第一个等号
            cookie_dict[key.strip()] = value.strip()

    return cookie_dict
def cookie_merge(old_cookie, new_cookie):
    """
    合并更新cookie，支持字典和字符串两种格式

    Args:
        old_cookie (dict or str): 旧cookie
        new_cookie (dict or str): 新cookie

    Returns:
        dict or str: 合并后的cookie，格式与old_cookie保持一致
    """
    # 判断输入类型
    old_is_dict = isinstance(old_cookie, dict)
    new_is_dict = isinstance(new_cookie, dict)

    # 统一转换为字典格式进行处理
    if old_is_dict:
        old_dict = old_cookie.copy()
    else:
        old_dict = cookie_string_to_dict(old_cookie)

    if new_is_dict:
        new_dict = new_cookie
    else:
        new_dict = cookie_string_to_dict(new_cookie)

    # 合并cookie，新cookie覆盖旧cookie
    merged_dict = {**old_dict, **new_dict}

    # 根据原始格式返回结果
    if old_is_dict:
        return merged_dict
    else:
        return cookie_dict_to_string(merged_dict)



if __name__ == '__main__':
    pass


