
import ast
import os
import random
from datetime import datetime

import cv2
from fake_useragent import UserAgent

import config


def get_user_agents():
    """
    获取默认UA列表。
    
    :return: UA列表。
    """
    try:
        with open(config.USER_AGENTS_PATH, "r", encoding='utf-8') as file:
            user_agents = [line.strip() for line in file if line.strip()]
        return user_agents
    except FileNotFoundError:
        print("User-Agent file not found.")
        return []


def get_random_user_agent():
    """
    获取随机UA。
    
    :return: 随机UA。
    """
    try:
        ua = UserAgent(platforms='desktop')  # 获取随机UA,筛选为桌面设备
        print((f'使用随机UA: {ua}'))
    except Exception as e:
        print(f"UA生成失败: {e}")  
        user_agents = get_user_agents()
        ua = random.choice(user_agents)
        print((f'使用随机UA【备用】: {ua}'))
    return ua


def get_proxies():
    """
    获取代理列表。
    
    :return: 代理列表。
    """
    try:
        with open(config.PROXIES_PATH, "r", encoding='utf-8') as file:
            proxies = [line.strip() for line in file if line.strip()]
        return proxies
    except FileNotFoundError:
        print("Proxies file not found.")
        return []


def get_random_proxy():
    """
    获取随机代理。
    
    :return: 随机代理。
    """
    proxies = get_proxies()
    return random.choice(proxies) if proxies else None


def save_set_to_txt(data_set, file_path):
    """
    将数据集保存到文本文件中。
    
    :param data_set: 要保存的数据集。
    :param file_path: 文件路径。
    """
    with open(file_path, 'w') as f:
        for item in data_set:
            f.write(f"{item}\n")


def get_formatted_timestamp():
    """
    获取当前时间戳并格式化为 年_月_日_时_分_秒_毫秒 格式。

    return: formatted_timestamp - 格式化后的时间戳字符串。
    """
    # 获取当前时间
    now = datetime.now()

    # 格式化时间戳
    formatted_timestamp = now.strftime("%Y_%m_%d_%H_%M_%S_%f")[:-3]  # 去掉微秒的最后三位

    return formatted_timestamp


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。
    :return: 读取的list。
    """
    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


def check_video_type(video_path):
    """
    判断视频是 RGB 还是 IR（红外）。
    
    :param video_path: 视频路径。
    :return: 视频类型。
    """
    cap = cv2.VideoCapture(video_path)

    if not cap.isOpened():
        print("无法打开视频")
        return None

    ret, frame = cap.read()  # 读取第一帧
    cap.release()

    if not ret:
        print("无法读取视频帧")
        return None

    # 获取通道数
    channels = frame.shape[-1] if len(frame.shape) == 3 else 1

    if channels == 3:
        return 'RGB'
    elif channels == 1:
        return 'IR'
    else:
        return 'RGB'
