import qbittorrentapi

class QBittorrentManager:
    def __init__(self, config):
        self.client = qbittorrentapi.Client(**config)

    def test_connection(self):
        try:
            self.client.auth_log_in()
            version = self.client.app.version
            api_version = self.client.app.webapi_version
            return True, f"连接成功，qBittorrent 版本: {version} (API: {api_version})"
        except qbittorrentapi.LoginFailed as e:
            return False, f"登录失败: {e}"
        except Exception as e:
            return False, f"连接失败: {e}"

    def get_stats(self):
        try:
            self.client.auth_log_in()
            return len(self.client.torrents_info())
        except:
            return 0

    def add_torrent(self, url):
        try:
            self.client.auth_log_in()
            result = self.client.torrents_add(urls=url)
            return result == "Ok.", "任务添加成功" if result == "Ok." else "任务添加失败"
        except Exception as e:
            return False, str(e)
