import os
import sys
import time
from model.custom_struct import GameConfig
from model.global_manager import GM
from model.helper import MyHelper
from net.task_api import task_api
from task.task import Task
from tools.log import logger
from tools.thread_pool import MyThreadPoolExecutor
from tools.utils import Utils
# 这些库都是打包需要的
import keyboard
import filelock
import cv2
import aiofiles
import aiopytesseract
import altgraph
import annotated
import annotated_types
import anyio
import attrs
import cattrs
import certifi
import chardet
import charset_normalizer
import colorama
import comtypes
import distro
import h11
import httpcore
import httpx
import idna
import jiter
import mss
import numpy
import openai
import packaging
import pefile
from PIL import Image
import pydantic
import pydantic_core
import pygetwindow as gw
import requests
import sniffio
import tqdm
import typing
import urllib3
import winshell
import tzdata
import tn
import dateutil
def main():
    try:
        # 初始化全局管理
        GM.init()
        # 创建线程池
        executor = MyThreadPoolExecutor(max_workers=GM.device_info.window_nums)
        timer = Utils.Timer()
        while GM.get_global_control():
            if timer.timer('heartbeat', 60):
                result,message = task_api.heartbeat(GM.device_info.officer)
                logger.info(f'心跳:{message}')
            idle_worker_count = executor.get_idle_worker_count()
            # 只有当有空闲工作线程时才继续
            if idle_worker_count > 0:
                window_list = task_api.get_window_list()
                for window in window_list:
                    window_id = window.window_id
                    # 只处理状态为 0 的窗口
                    if GM.get_window_status(window_id) == 0:
                        # 检查更新
                        GM.updater.check_updates(GM.device_info, window.game_list)
                        # 检查是否有任务需要执行
                        for game in window.game_list:
                            game_info = GameConfig.dict_to_GameConfig(game)
                            if GM.updater.get_is_updating(game_info.task_id):  # 检查是否正在更新
                                continue
                            if not game_info.is_execute:
                                continue
                            # 取账号信息
                            result, account_info = task_api.get_account(game_info.task_id,GM.device_info.only_new,GM.device_info.only_retained)
                            logger.info(f'[窗口-{window_id}]{game_info.task_id}-获取账号:{account_info}',window_id)
                            if result:
                                task_api.up_log_profession(account_info.account, game_info.task_id, '拉取账号', '成功')
                                helper = MyHelper(window_id, game_info, account_info)
                                # 设置窗口状态为正在执行
                                GM.set_window_status(window_id, 1)
                                # 提交任务给线程池异步执行
                                executor.submit(Task(helper).run)
                                break  # 处理完一个窗口任务后，跳出当前循环，避免重复提交任务
                            time.sleep(3)
            time.sleep(10)  # 等待一定时间后重新检查
    except Exception as e:
        logger.exception(f'主线程异常:{e}')




if __name__ == '__main__':

    if Utils.is_admin():
        main()
        sys.exit()
    else:
        Utils.run_as_admin()
