"""Single-source duration node for MiniMax H3 / PRISM2 graphs.

One ``seconds`` widget drives every duration-shaped value in the workflow:

* ``length``         INT    frame count for MiniMaxH3ImageToVideo
* ``fps``            FLOAT  forwarded to CreateVideo
* ``seconds``        FLOAT  snapped duration for H3PromptValidate
* ``duration_text``  STRING two-decimal text, e.g. ``8.00`` (no unit word)
* ``report``         STRING what the snap/clamp actually did

The frame grid matches ``MiniMaxH3ImageToVideo`` (``align_frame_count``):

    n = max(5, round(seconds * fps))
    while n % 17 != 5:
        n += 1

so a length emitted here is stable when the H3 node snaps again.
``clamp_trained`` then pulls that result onto the trained endpoints 124 and
362. Both endpoints already satisfy ``n % 17 == 5``, so the clamp cannot
throw the value off the grid.

``seconds`` and ``duration_text`` describe the length that will actually be
sampled, not the number typed into the widget. 7.5 s at 24 fps becomes
192 frames and ``8.00``.

This file is a drop-in for ``h3_timing.py``. The class name stays
``H3Timing``. Do not load both files in ``custom_nodes`` at once.
"""

import math

FRAME_STEP = 17
FRAME_OFFSET = 5
TRAINED_MIN = 124  # 17 * 7 + 5
TRAINED_MAX = 362  # 17 * 21 + 5


def align_frame_count(n):
    """Snap up onto ``17k + 5`` (``n % 17 == 5``), same loop the H3 node uses.

    Values below 5 are lifted to 5 first, which is itself on the grid
    (k = 0). The loop adds at most 16 frames.
    """
    n = max(FRAME_OFFSET, int(n))
    while n % FRAME_STEP != FRAME_OFFSET:
        n += 1
    return n


class H3Timing:
    CATEGORY = "H3/utility"
    FUNCTION = "compute"
    RETURN_TYPES = ("INT", "FLOAT", "FLOAT", "STRING", "STRING")
    RETURN_NAMES = ("length", "fps", "seconds", "duration_text", "report")
    DESCRIPTION = (
        "整个工作流只改 seconds。输出 H3 帧数、fps、吸附后的秒数、"
        "提示词里的两位时长文本，以及一句吸附说明。"
    )

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "seconds": ("FLOAT", {
                    "default": 8.0,
                    "min": 1.0,
                    "max": 60.0,
                    "step": 0.01,
                    "tooltip": (
                        "想要的视频时长（秒）。真正写进图里的是吸附之后的秒数："
                        "7.5 会变成 8.00。训练区间大约 5.17–15.08 秒（24 fps）。"
                    ),
                }),
                "fps": ("FLOAT", {
                    "default": 24.0,
                    "min": 1.0,
                    "max": 120.0,
                    "step": 1.0,
                    "tooltip": (
                        "同时送给 CreateVideo 的帧率。H3 模型按 24 fps 训练，"
                        "改这个数会改变播放速度，不会改变模型内部的时间刻度。"
                    ),
                }),
                "snap_17k5": ("BOOLEAN", {
                    "default": True,
                    "tooltip": (
                        "按 H3 的 17k+5 网格向上对齐（与 MiniMaxH3ImageToVideo 相同）。"
                        "关掉之后 H3 节点仍会自己再吸附一次，时长文本可能对不上。"
                    ),
                }),
                "clamp_trained": ("BOOLEAN", {
                    "default": True,
                    "tooltip": "把帧数限制在官方训练区间 124~362（两端都在 17k+5 网格上）。",
                }),
            },
        }

    def compute(self, seconds, fps, snap_17k5, clamp_trained):
        fps_value = float(fps)
        if not math.isfinite(fps_value) or fps_value <= 0:
            fps_value = 24.0
        requested = float(seconds)
        if not math.isfinite(requested):
            requested = 8.0
        raw = int(round(requested * fps_value))
        if raw < 1:
            raw = 1
        snapped = False
        if snap_17k5:
            frames = align_frame_count(raw)
            snapped = frames != raw
        else:
            frames = raw
        clamped = False
        if clamp_trained:
            if frames < TRAINED_MIN:
                frames = TRAINED_MIN
                clamped = True
            elif frames > TRAINED_MAX:
                frames = TRAINED_MAX
                clamped = True
        real = frames / fps_value
        # Two decimals match the prompt line "DURATION = 8.00 seconds"
        # and the published 17k+5 table (243/24 = 10.125 -> "10.12").
        text = "%.2f" % real
        notes = []
        if snapped:
            notes.append("snapped up to 17k+5")
        if clamped:
            notes.append("clamped to trained 124..362")
        if not snap_17k5:
            notes.append("snap off; H3 will still snap on its own")
        report = "requested %.2fs @ %g fps -> %d frames -> %ss" % (
            requested, fps_value, int(frames), text,
        )
        if notes:
            report = "%s (%s)" % (report, "; ".join(notes))
        return (int(frames), float(fps_value), round(real, 4), text, report)


NODE_CLASS_MAPPINGS = {"H3Timing": H3Timing}
NODE_DISPLAY_NAME_MAPPINGS = {"H3Timing": "H3 时长（单一入口）"}


def _expect(actual, expected, label):
    if actual != expected:
        raise SystemExit("%s: got %s, expected %s" % (label, actual, expected))


def _self_test():
    node = H3Timing()
    table = {
        124: "5.17",
        141: "5.88",
        158: "6.58",
        175: "7.29",
        192: "8.00",
        209: "8.71",
        226: "9.42",
        243: "10.12",
        260: "10.83",
        277: "11.54",
        294: "12.25",
        311: "12.96",
        328: "13.67",
        345: "14.38",
        362: "15.08",
    }
    for frames, text in table.items():
        _expect(align_frame_count(frames), frames, "grid %d" % frames)
        length, fps, seconds, duration_text, _report = node.compute(
            frames / 24.0, 24.0, True, True,
        )
        _expect(length, frames, "length for %d" % frames)
        _expect(fps, 24.0, "fps")
        _expect(duration_text, text, "text for %d" % frames)
        _expect(seconds, round(frames / 24.0, 4), "seconds for %d" % frames)

    # 7.5 s is not on the grid: 180 frames snap up to 192 = 8.00 s.
    length, _fps, seconds, text, report = node.compute(7.5, 24.0, True, True)
    _expect((length, seconds, text), (192, 8.0, "8.00"), "7.5s snap")
    if "8.00" not in report or "192" not in report:
        raise SystemExit("report missing snap detail: %s" % report)

    # Below the trained range: 3 s -> 73 frames on the grid, then clamp to 124.
    length, _fps, seconds, text, report = node.compute(3.0, 24.0, True, True)
    _expect((length, text), (124, "5.17"), "3s clamp")
    if "clamped" not in report:
        raise SystemExit("report missing clamp: %s" % report)

    # Above the trained range: 20 s snaps past 362, then clamps back to 362.
    length, _fps, _seconds, text, _report = node.compute(20.0, 24.0, True, True)
    _expect((length, text), (362, "15.08"), "20s clamp")

    # 15.0 s * 24 = 360, which snaps up to 362 (still inside the clamp).
    length, _fps, _seconds, text, _report = node.compute(15.0, 24.0, True, True)
    _expect((length, text), (362, "15.08"), "15s snap")

    # Exact 8.00 s is unchanged, so a patched 192-frame graph does not drift.
    length, fps, seconds, text, _report = node.compute(8.0, 24.0, True, True)
    _expect((length, fps, seconds, text), (192, 24.0, 8.0, "8.00"), "8s identity")

    # Snap off does not invent a grid length. H3 itself may still snap later.
    length, _fps, _seconds, text, report = node.compute(7.5, 24.0, False, False)
    _expect((length, text), (180, "7.50"), "snap off")
    if "snap off" not in report:
        raise SystemExit("report missing snap-off note: %s" % report)

    print("h3_timing.v2 self-test ok")


if __name__ == "__main__":
    _self_test()
