#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""等另一条会话的 v3_tts_all.py 进程退出且内存充足，再允许本会话加载 VoxCPM2。"""
import ctypes
import time

PIDS = [17704, 17088]          # 平行会话 v3 TTS 的父子进程
THRESHOLD = 6.0 * 1e9
MAX_WAIT_S = 540


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


def alive(pid):
    k = ctypes.windll.kernel32
    h = k.OpenProcess(0x1000, False, pid)   # PROCESS_QUERY_LIMITED_INFORMATION
    if h:
        k.CloseHandle(h)
        return True
    return False


start = time.time()
print("start %s | avail %.2f GB | alive pids %s" % (
    time.strftime("%H:%M:%S"), avail() / 1e9, [p for p in PIDS if alive(p)]), flush=True)
while time.time() - start < MAX_WAIT_S:
    a = avail()
    running = [p for p in PIDS if alive(p)]
    if not running and a >= THRESHOLD:
        print("READY %s | avail %.2f GB | v3_tts_all 已退出 | waited %.1f min" % (
            time.strftime("%H:%M:%S"), a / 1e9, (time.time() - start) / 60), flush=True)
        raise SystemExit(0)
    if int(time.time() - start) % 60 < 1:
        print("  wait %s avail %.2f GB alive=%s" % (
            time.strftime("%H:%M:%S"), a / 1e9, running), flush=True)
    time.sleep(15)
print("TIMEOUT %s | avail %.2f GB | alive %s" % (
    time.strftime("%H:%M:%S"), avail() / 1e9,
    [p for p in PIDS if alive(p)]), flush=True)
raise SystemExit(2)
