#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""2026-10-07 DSH 补丁：给 ComfyUI_MiniMaxH3_Director 的段缓存加载加「诊断 + 强制复用」。

背景：段缓存判据是「指纹完全相等」，任何一项不等就静默重算；二采路径连日志都不打。
      掉电/重启/误改参数后，磁盘上明明有 latent 却无法复用，白跑数小时。

只改 director/segment_cache.py：
  F1a  一采缓存 meta/av.pt 缺失 → 打 WARNING（原来静默 return None）
  F1a' 最终 AV 缓存 meta/av.pt 缺失 → 打 WARNING
  F1b  一采指纹不等 → WARNING + 打印差在哪些键（原来 INFO，且往往看不到）
  F1b' 二采指纹不等 → WARNING + diff（原来完全没有日志）
  F2   逃生门（**调用时读取，无需重启即可开关**）：
         H3_DIRECTOR_CACHE_ALLOW_STALE=1   或  存在文件 ~/.h3_cache_allow_stale
             → 指纹不等也复用磁盘上的 latent（打 WARNING）
         H3_DIRECTOR_CACHE_IGNORE=source_video,ref_max   或  ~/.h3_cache_ignore
             → 这些键不参与比较
     默认（都不设/文件不存在）= 行为与原来完全一致，只是日志更清楚。

用法：python3 cache_reuse_patch.py [--apply]
"""
import argparse
import ast
import shutil
import sys
from pathlib import Path

TARGET = Path("/home/zyw/ComfyUI/custom_nodes/ComfyUI_MiniMaxH3_Director/director/segment_cache.py")
BACKUP_SUFFIX = ".bak-20261007-cachefix"

HELPERS = '''
# ---- 2026-10-07 DSH patch: 段缓存复用诊断 + 强制复用逃生门（默认关闭，行为不变）----
# 开关在**调用时**读取：支持环境变量，也支持 touch/rm 一个文件即时生效（不必重启 ComfyUI）。
import os as _os


def _cache_allow_stale() -> bool:
    try:
        if str(_os.environ.get("H3_DIRECTOR_CACHE_ALLOW_STALE", "")).strip().lower() in {"1", "true", "yes", "on"}:
            return True
        return _os.path.isfile(_os.path.expanduser("~/.h3_cache_allow_stale"))
    except Exception:
        return False


def _cache_ignore_keys() -> set:
    raw = str(_os.environ.get("H3_DIRECTOR_CACHE_IGNORE", ""))
    try:
        p = _os.path.expanduser("~/.h3_cache_ignore")
        if _os.path.isfile(p):
            with open(p, encoding="utf-8") as fh:
                raw += "," + fh.read().strip()
    except Exception:
        pass
    return {k.strip() for k in raw.split(",") if k.strip()}


def _fp_view(fp):
    """按忽略清单过滤后的指纹视图。"""
    if not isinstance(fp, dict):
        return fp
    ignore = _cache_ignore_keys()
    if not ignore:
        return fp
    return {k: v for k, v in fp.items() if k not in ignore}


def _fp_same(stored, expected):
    return _fp_view(stored) == _fp_view(expected)
# ---- end DSH patch ----
'''

PATCHES = [
    # ── F1a：一采缓存缺文件（用 .pre.* 上下文保证锚点唯一）
    (
        "    meta_path = root / f\"seg_{idx:04d}.pre.meta.json\"\n"
        "    latent_path = root / f\"seg_{idx:04d}.pre.av.pt\"\n"
        "    frames_path = root / f\"seg_{idx:04d}.pre.pt\"\n"
        "    handoff_path = root / f\"seg_{idx:04d}.pre.handoff.json\"\n"
        "    if not meta_path.is_file() or not latent_path.is_file():\n"
        "        return None\n",
        "    meta_path = root / f\"seg_{idx:04d}.pre.meta.json\"\n"
        "    latent_path = root / f\"seg_{idx:04d}.pre.av.pt\"\n"
        "    frames_path = root / f\"seg_{idx:04d}.pre.pt\"\n"
        "    handoff_path = root / f\"seg_{idx:04d}.pre.handoff.json\"\n"
        "    if not meta_path.is_file() or not latent_path.is_file():\n"
        "        log.warning(\n"
        "            \"Segment %d first-pass cache unusable: missing %s (meta=%s, av=%s) -> will sample.\",\n"
        "            idx + 1,\n"
        "            \"meta\" if not meta_path.is_file() else \"av-latent\",\n"
        "            meta_path.is_file(),\n"
        "            latent_path.is_file(),\n"
        "        )\n"
        "        return None\n",
    ),
    # ── F1a'：最终 AV latent 缓存缺文件
    (
        "    meta_path = root / f\"seg_{idx:04d}.meta.json\"\n"
        "    latent_path = root / f\"seg_{idx:04d}.av.pt\"\n"
        "    if not meta_path.is_file() or not latent_path.is_file():\n"
        "        return None\n",
        "    meta_path = root / f\"seg_{idx:04d}.meta.json\"\n"
        "    latent_path = root / f\"seg_{idx:04d}.av.pt\"\n"
        "    if not meta_path.is_file() or not latent_path.is_file():\n"
        "        log.warning(\n"
        "            \"Segment %d final AV cache unusable: missing %s (meta=%s, av=%s) -> will recompute.\",\n"
        "            idx + 1,\n"
        "            \"meta\" if not meta_path.is_file() else \"av-latent\",\n"
        "            meta_path.is_file(),\n"
        "            latent_path.is_file(),\n"
        "        )\n"
        "        return None\n",
    ),
    # ── F1b/F2：一采指纹比较
    (
        "        if not isinstance(stored, dict) or stored != expected or missing_external:\n",
        "        _fp_hit = isinstance(stored, dict) and _fp_same(stored, expected)\n"
        "        if not _fp_hit and _cache_allow_stale() and isinstance(stored, dict) and latent_path.is_file():\n"
        "            log.warning(\n"
        "                \"Segment %d first-pass cache MISMATCH but reusing anyway \"\n"
        "                \"(H3_DIRECTOR_CACHE_ALLOW_STALE / ~/.h3_cache_allow_stale): diff=%s\",\n"
        "                idx + 1,\n"
        "                _fingerprint_diff_keys(stored, expected)[:8],\n"
        "            )\n"
        "            _fp_hit = True\n"
        "        if not _fp_hit or missing_external:\n",
    ),
    (
        "            log.info(\n"
        "                \"Segment %d first-pass cache miss (diff=%s); will sample first pass.\",\n",
        "            log.warning(\n"
        "                \"Segment %d first-pass cache miss (diff=%s); will sample first pass.\",\n",
    ),
    # ── F1b'/F2：二采（最终）指纹比较
    (
        "        stored = json.loads(meta_path.read_text(encoding=\"utf-8\"))\n"
        "        expected = segment_cache_fingerprint(seg, plan)\n"
        "        if stored == expected:\n"
        "            return True\n"
        "        if _reject_source_stale(stored, expected, seg_index=seg.index, quiet=True):\n"
        "            return False\n"
        "        return bool(allow_stale and tensor_path.is_file())\n",
        "        stored = json.loads(meta_path.read_text(encoding=\"utf-8\"))\n"
        "        expected = segment_cache_fingerprint(seg, plan)\n"
        "        if _fp_same(stored, expected):\n"
        "            return True\n"
        "        _diff = _fingerprint_diff_keys(stored, expected)\n"
        "        if _cache_allow_stale() and tensor_path.is_file():\n"
        "            log.warning(\n"
        "                \"Segment %d final(refine) cache MISMATCH but reusing anyway \"\n"
        "                \"(H3_DIRECTOR_CACHE_ALLOW_STALE / ~/.h3_cache_allow_stale): diff=%s\",\n"
        "                seg.index + 1,\n"
        "                _diff[:8],\n"
        "            )\n"
        "            return True\n"
        "        log.warning(\n"
        "            \"Segment %d final(refine) cache mismatch (diff=%s); will recompute refine.\",\n"
        "            seg.index + 1,\n"
        "            _diff[:8],\n"
        "        )\n"
        "        if _reject_source_stale(stored, expected, seg_index=seg.index, quiet=True):\n"
        "            return False\n"
        "        return bool(allow_stale and tensor_path.is_file())\n",
    ),
]


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--apply", action="store_true")
    a = ap.parse_args()

    src = TARGET.read_text(encoding="utf-8")
    if "_CACHE_ALLOW_STALE" in src or "_cache_allow_stale" in src:
        print("[skip] 补丁似乎已经打过。")
        return 0

    out = src
    anchor = 'log = logging.getLogger("ComfyUI-MiniMaxH3-Director.director.cache")\n'
    if anchor not in out:
        print("[FAIL] 找不到 logger 定义锚点")
        return 2
    out = out.replace(anchor, anchor + HELPERS, 1)

    for old, new in PATCHES:
        cnt = out.count(old)
        if cnt != 1:
            print(f"[FAIL] 锚点出现 {cnt} 次（应 1 次）:\n" + old[:140])
            return 2
        out = out.replace(old, new, 1)

    ast.parse(out)
    print("[ok] 5 处替换完成，语法检查通过")

    if not a.apply:
        print("[dry-run] 未写入。加 --apply 生效。")
        return 0

    bak = Path(str(TARGET) + BACKUP_SUFFIX)
    if not bak.exists():
        shutil.copy2(TARGET, bak)
        print(f"[ok] 备份 -> {bak}")
    TARGET.write_text(out, encoding="utf-8")
    print(f"[ok] 已写入 {TARGET}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
