#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 fix10 重录守护 v2：等所有 VoxCPM 占用进程退出后再录。
v1 只盯 PID 31844，对方 12:21:48 又起了一个 PID 13616（EP2 三句重录），
我在 12:19 抢跑，模型加载到 safetensors 时 0xC0000005 崩溃（rc=3221225477）。
v2 改成按「python 进程 WS>2.5GB 或命令行含 VoxCPM」识别占用者，
必须清空 + 可用物理>=6.5GB + 可用页文件>=6GB，连续稳定 90s 才启动。
绝不杀对方进程；最多等 120 分钟。"""
import ctypes, datetime, json, os, subprocess, sys, time

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

HERE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.join(HERE, "ep03_fix10_wait_run_v2.log")
PY = r"D:\voxcpm\.venv\Scripts\python.exe"
TTS = os.path.join(HERE, "ep03_fix10_tts.py")
MIN_FREE_GB = 6.5
MIN_PAGE_GB = 6.0
SETTLE_S = 90
MAX_WAIT_MIN = 120


def log(msg):
    line = "[%s] %s" % (datetime.datetime.now().strftime("%H:%M:%S"), msg)
    print(line, flush=True)
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(line + "\n")


def mem():
    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)]
    m = M()
    m.dwLength = ctypes.sizeof(M)
    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
    return m.ullAvailPhys / (1024 ** 3), m.ullAvailPageFile / (1024 ** 3)


PS = ("Get-CimInstance Win32_Process | Where-Object { "
      "($_.Name -match '^pythonw?\\.exe$' -and $_.WorkingSetSize -gt 2500000000) "
      "-or ($_.CommandLine -match 'VoxCPM|voxcpm' -and $_.Name -match '^pythonw?\\.exe$') "
      "} | ForEach-Object { \"$($_.ProcessId):$([math]::Round($_.WorkingSetSize/1GB,2))\" }")


def blockers():
    try:
        out = subprocess.run(["powershell", "-NoProfile", "-Command", PS],
                             capture_output=True, timeout=25).stdout
        if isinstance(out, bytes):
            out = out.decode("utf-8", "replace")
        return [s.strip() for s in (out or "").splitlines() if s.strip()]
    except Exception as e:
        return ["PROBE_ERR:%s" % e]


def main():
    log("WAIT START v2: min_free=%.1fGB min_page=%.1fGB settle=%ds max_wait=%dmin" %
        (MIN_FREE_GB, MIN_PAGE_GB, SETTLE_S, MAX_WAIT_MIN))
    t0 = time.time()
    last_report = 0
    while time.time() - t0 < MAX_WAIT_MIN * 60:
        bl = blockers()
        free, pagefree = mem()
        if time.time() - t0 - last_report >= 120:
            log("waiting: blockers=%s free=%.2fGB pagefree=%.2fGB" % (bl, free, pagefree))
            last_report = time.time()
        if not bl and free >= MIN_FREE_GB and pagefree >= MIN_PAGE_GB:
            log("CLEAR: blockers=[] free=%.2fGB pagefree=%.2fGB -> settle %ds" %
                (free, pagefree, SETTLE_S))
            time.sleep(SETTLE_S)
            bl2 = blockers()
            free2, pagefree2 = mem()
            log("after settle: blockers=%s free=%.2fGB pagefree=%.2fGB" % (bl2, free2, pagefree2))
            if bl2 or free2 < 5.5 or pagefree2 < 5.0:
                log("CONDITION LOST -> back to waiting")
                continue
            # 加载探针：崩溃则不再跑 8 take，留现场给人工判断
            probe = subprocess.run([PY, "-u", "-c",
                                    'from voxcpm import VoxCPM; '
                                    'm=VoxCPM.from_pretrained(r"D:\\voxcpm\\models\\models\\'
                                    'OpenBMB--VoxCPM2\\snapshots\\master", '
                                    'load_denoiser=False, device="cpu", optimize=False); '
                                    'print("LOAD_OK", flush=True)'],
                                   cwd=HERE, capture_output=True, timeout=300)
            tail = (probe.stderr or b"").decode("utf-8", "replace")[-500:]
            log("load probe rc=%d tail=%s" % (probe.returncode, tail.replace("\n", " | ")))
            if probe.returncode != 0:
                log("LOAD PROBE FAILED - abort, no TTS launched")
                return
            time.sleep(10)
            with open(os.path.join(HERE, "ep03_fix10_tts.log"), "a", encoding="utf-8") as f:
                f.write("\n=== retry %s ===\n" % datetime.datetime.now().strftime("%H:%M:%S"))
            p = subprocess.Popen([PY, "-u", TTS], cwd=HERE,
                                 stdout=open(os.path.join(HERE, "ep03_fix10_tts.log"), "a", encoding="utf-8"),
                                 stderr=subprocess.STDOUT)
            log("TTS launched PID=%d" % p.pid)
            rc = p.wait()
            log("TTS finished rc=%d" % rc)
            return
        time.sleep(20)
    log("TIMEOUT after %d min; blockers=%s" % (MAX_WAIT_MIN, blockers()))


if __name__ == "__main__":
    main()
