from services.cursor_service import CursorService
from common_utils import get_hardware_id
from exit_cursor import ExitCursor
from PyQt5.QtCore import QThread, pyqtSignal

class BaseWorker(QThread):
    """基础工作线程类"""
    progress = pyqtSignal(dict)  # 进度信号
    finished = pyqtSignal(tuple)  # 完成信号
    error = pyqtSignal(str)      # 错误信号

    def __init__(self):
        super().__init__()
        self._is_running = True

    def stop(self):
        """停止线程"""
        self._is_running = False
        self.wait()

class RefreshTokenWorker(BaseWorker):
    """刷新 Cursor Token 工作线程"""
    def run(self):
        try:
            service = CursorService()
            machine_id = get_hardware_id()
            
            # 更新进度 - 退出 Cursor
            self.progress.emit({
                "status": "exiting",
                "message": "正在关闭 Cursor 进程..."
            })
            
            # 退出 Cursor
            if not ExitCursor():
                raise Exception("无法完全关闭 Cursor 进程，请手动关闭后重试")
            
            # 更新进度 - 开始刷新
            self.progress.emit({
                "status": "refreshing",
                "message": "正在刷新 Cursor 授权..."
            })
            
            # 调用刷新服务
            success, msg, account_info = service.refresh_account(machine_id)
            
            if success and account_info:
                # 更新进度 - 开始重置机器码
                self.progress.emit({
                    "status": "resetting",
                    "message": "正在重置机器码..."
                })
                
                # 调用重置机器码
                reset_success, reset_msg, reset_data = service.reset_machine()
                
                if reset_success:
                    # 更新进度
                    self.progress.emit({
                        "status": "success",
                        "message": f"授权刷新成功: {account_info.get('email')}"
                    })
                    
                    result_msg = (
                        f"授权刷新成功\n"
                        f"账号: {account_info.get('email')}\n"
                        f"到期时间: {account_info.get('expire_time')}\n"
                        f"剩余天数: {account_info.get('days_left')}天\n\n"
                        f"机器码重置成功\n"
                        f"请重新启动 Cursor 编辑器"
                    )
                else:
                    result_msg = f"授权刷新成功，但机器码重置失败: {reset_msg}"
            else:
                result_msg = f"授权刷新失败: {msg}"
            
            self.finished.emit(('refresh', (success, result_msg)))
            
        except Exception as e:
            self.error.emit(str(e))

class ResetWorker(BaseWorker):
    """重置机器码工作线程"""
    def run(self):
        try:
            service = CursorService()
            success, msg, data = service.reset_machine()
            self.finished.emit(('reset', (success, msg, data)))
        except Exception as e:
            self.error.emit(str(e))

class DisableWorker(BaseWorker):
    """禁用更新工作线程"""
    def run(self):
        try:
            service = CursorService()
            success, msg = service.disable_update()
            self.finished.emit(('disable', (success, msg)))
        except Exception as e:
            self.error.emit(str(e)) 