"""浏览器池管理模块 - 单例模式确保状态共享"""
import random
from typing import Optional, Tuple
import os
from DrissionPage import ChromiumPage, ChromiumOptions
import platform
from DrissionPage.common import Settings

Settings.set_raise_when_click_failed(True)


class BrowserManager:
    """浏览器池管理器 - 使用单例模式"""
    _instance = None

    def __init__(self):
        self.cache_path = os.path.join(os.getcwd(), ".cache")

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.browser_pool = {}
        return cls._instance

    def create_browser(self, user_agent: str = None) -> Tuple[int, ChromiumPage]:
        """创建新的浏览器实例"""
        random_port = random.randint(9223, 9934)
        while random_port in self.browser_pool:
            random_port = random.randint(9223, 9934)

        co = ChromiumOptions().set_local_port(random_port)
        if user_agent:
            co.set_user_agent(user_agent)
        if platform.system() != 'Windows':
            co.set_argument('--no-sandbox')
        custom_data_dir = os.path.join(os.path.expanduser('~'), 'DrissionPage', "userData", f"{random_port}")
        co.set_user_data_path(custom_data_dir)  # 设置用户数据路径
        # if not os.path.exists(custom_data_dir):
        #     os.makedirs(custom_data_dir)
        self.browser_pool[random_port] = ChromiumPage(co)
        return random_port, self.browser_pool[random_port]

    def get_browser(self, port: int) -> Optional[ChromiumPage]:
        """根据端口获取浏览器实例"""
        return self.browser_pool.get(port)

    def remove_browser(self, port: int) -> Tuple[bool, Optional[ChromiumPage]]:
        """根据端口移除浏览器实例"""
        browser = self.browser_pool.pop(port, None)
        return browser is not None, browser

    def list_browsers(self) -> list[int]:
        """列出所有活跃的浏览器端口"""
        return list(self.browser_pool.keys())

    def set_cache_path(self, path: str) -> None:
        self.cache_path = os.path.join(path, ".cache")

    def get_cache_path(self) -> Optional[str]:
        if not os.path.exists(self.cache_path):
            os.makedirs(self.cache_path)
        return self.cache_path


# 创建全局单例实例
browser_manager = BrowserManager()
