import ctypes
import time

VK_F15 = 0x7E
KEYEVENTF_KEYUP = 0x2


# 主显示器分辨率阈值：当前分辨率不超过此尺寸时视为远程（可改为你本机分辨率上限）
_REMOTE_RESOLUTION_MAX_WIDTH = 1920
_REMOTE_RESOLUTION_MAX_HEIGHT = 1080

SM_CXSCREEN = 0
SM_CYSCREEN = 1


def _is_remote_session() -> bool:
    """根据主显示器分辨率判断是否在远程：分辨率不超过阈值时视为远程会话。"""
    user32 = ctypes.windll.user32
    w = user32.GetSystemMetrics(SM_CXSCREEN)
    h = user32.GetSystemMetrics(SM_CYSCREEN)
    return w <= _REMOTE_RESOLUTION_MAX_WIDTH and h <= _REMOTE_RESOLUTION_MAX_HEIGHT


def command_keep_awake() -> None:
    """每 4 分钟模拟一次 F15 按键，阻止系统休眠（仅远程桌面会话生效）"""
    print("防休眠已启动，每 4 分钟检测一次（Ctrl+C 退出）")
    try:
        while True:
            if _is_remote_session():
                ctypes.windll.user32.keybd_event(VK_F15, 0, 0, 0)
                ctypes.windll.user32.keybd_event(VK_F15, 0, KEYEVENTF_KEYUP, 0)
            time.sleep(240)
    except KeyboardInterrupt:
        print("\n已停止。")
