"""Single-source duration helper for MiniMax H3 video graphs.

H3 wants a frame count (`MiniMaxH3ImageToVideo.length`) on the 17k+5 grid at 24 fps,
while a graph usually also repeats the duration in three other places:
  * `H3PromptValidate.duration` (seconds)
  * the `DURATION = 8.00 seconds` line inside the task prompt
  * `CreateVideo.fps` (which turns frames back into seconds)

This node computes all of them from one `seconds` value so nothing can drift.

Alignment rule (copied from the H3 node tooltip: "snapped up to the 17k+5 grid"):
    length = 17 * ceil((round(seconds * fps) - 5) / 17) + 5
    real_seconds = length / fps
e.g. 8.0 s -> 192 frames (exact), 7.5 s -> 192 frames (8.00 s, the grid cannot do 7.5).
"""

import math

FRAME_STEP = 17
FRAME_OFFSET = 5


class H3Timing:
    CATEGORY = "H3/utility"
    FUNCTION = "compute"
    RETURN_TYPES = ("INT", "FLOAT", "FLOAT", "STRING")
    RETURN_NAMES = ("length", "fps", "seconds", "duration_text")

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "seconds": ("FLOAT", {
                    "default": 8.0, "min": 1.0, "max": 60.0, "step": 0.01,
                    "tooltip": "想要的视频时长（秒）。整个工作流只改这一个数。",
                }),
                "fps": ("FLOAT", {"default": 24.0, "min": 1.0, "max": 120.0, "step": 1.0}),
                "snap_17k5": ("BOOLEAN", {
                    "default": True,
                    "tooltip": "按 H3 的 17k+5 网格向上对齐（124≈5s，243≈10s，362≈15s）。",
                }),
                "clamp_trained": ("BOOLEAN", {
                    "default": True,
                    "tooltip": "把帧数限制在官方训练区间 124~362（更长未验证）。",
                }),
            },
        }

    def compute(self, seconds, fps, snap_17k5, clamp_trained):
        fps = float(fps) or 24.0
        raw = max(1, int(round(float(seconds) * fps)))
        if snap_17k5:
            frames = FRAME_STEP * math.ceil((raw - FRAME_OFFSET) / FRAME_STEP) + FRAME_OFFSET
            if frames < FRAME_OFFSET + FRAME_STEP:
                frames = FRAME_OFFSET + FRAME_STEP * max(1, math.ceil((raw - FRAME_OFFSET) / FRAME_STEP))
        else:
            frames = raw
        if clamp_trained:
            frames = min(max(frames, 124), 362)
        real = frames / fps
        return (int(frames), float(fps), round(real, 4), "%.2f" % real)


NODE_CLASS_MAPPINGS = {"H3Timing": H3Timing}
NODE_DISPLAY_NAME_MAPPINGS = {"H3Timing": "H3 时长 → 帧数 (单一入口)"}
