#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""等待可用物理内存 ≥5.2 GB，供 VoxCPM2 加载（不杀任何进程）。"""
import ctypes
import time

THRESHOLD = 5.2 * 1e9
MAX_WAIT_S = 900


class M(ctypes.Structure):
    _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
                ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
                ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
                ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
                ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]


def avail():
    m = M()
    m.dwLength = ctypes.sizeof(M)
    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
    return m.ullAvailPhys


start = time.time()
print("start %s | avail %.2f GB | threshold 5.20 GB | max wait %d min" % (
    time.strftime("%H:%M:%S"), avail() / 1e9, MAX_WAIT_S / 60), flush=True)
stable = 0
while time.time() - start < MAX_WAIT_S:
    a = avail()
    if a >= THRESHOLD:
        stable += 1
        if stable >= 2:   # 连续两次达标，避免瞬时波动
            print("READY %s | avail %.2f GB | waited %.1f min" % (
                time.strftime("%H:%M:%S"), a / 1e9, (time.time() - start) / 60), flush=True)
            raise SystemExit(0)
    else:
        stable = 0
    if int(time.time() - start) % 60 == 0:
        print("  wait %s avail %.2f GB" % (time.strftime("%H:%M:%S"), a / 1e9), flush=True)
    time.sleep(15)
print("TIMEOUT %s | avail %.2f GB | 未达标，需人工决定" % (
    time.strftime("%H:%M:%S"), avail() / 1e9), flush=True)
raise SystemExit(2)
