"""FikoYT Wan 2.2 T2V — text-to-video latent generation.

Wan-AI/Wan2.2-T2V-A14B MoE diffusion. ComfyUI core / Kijai WanVideoWrapper uyumlu.
Bu node MODEL + CONDITIONING alır, video latent (LATENT) döndürür.
Decode aşaması ayrı bir VAE Decode node ile yapılır.
"""
import os

try:
    import torch
    import comfy.samplers
    import comfy.sample
    import comfy.utils
    from nodes import common_ksampler
except ImportError:
    torch = None
    comfy = None
    common_ksampler = None

from ..core import normalize_seed


def _empty_video_latent(width: int, height: int, length: int, batch_size: int = 1):
    """Wan video latent — Wan VAE: spatial /8, temporal /4 + 1 frame."""
    # Wan 2.x latent shape: [B, 16, T_latent, H/8, W/8]
    t_latent = ((length - 1) // 4) + 1
    h_latent = height // 8
    w_latent = width // 8
    samples = torch.zeros([batch_size, 16, t_latent, h_latent, w_latent])
    return {"samples": samples}


class FikoYTWanT2V:
    """Wan 2.2 T2V — metinden video latent."""

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "model": ("MODEL",),
                "positive": ("CONDITIONING",),
                "negative": ("CONDITIONING",),
                "width": ("INT", {"default": 832, "min": 64, "max": 3072, "step": 8}),
                "height": ("INT", {"default": 1280, "min": 64, "max": 3072, "step": 8}),
                "length": ("INT", {"default": 81, "min": 1, "max": 1000}),
                "fps": ("INT", {"default": 24, "min": 1, "max": 60}),
                "steps": ("INT", {"default": 25, "min": 1, "max": 200}),
                "cfg": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 30.0, "step": 0.1}),
                "sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"default": "uni_pc"}),
                "scheduler": (comfy.samplers.KSampler.SCHEDULERS, {"default": "simple"}),
                "seed": ("INT", {"default": -1, "min": -1, "max": 0xFFFFFFFF}),
            }
        }

    RETURN_TYPES = ("LATENT", "INT")
    RETURN_NAMES = ("LATENT", "fps")
    FUNCTION = "generate"
    CATEGORY = "FikoYT/video"

    def generate(self, model, positive, negative, width, height, length, fps,
                 steps, cfg, sampler_name, scheduler, seed):
        seed = normalize_seed(seed)
        latent = _empty_video_latent(width, height, length)
        out = common_ksampler(
            model, seed, steps, cfg, sampler_name, scheduler,
            positive, negative, latent, denoise=1.0,
        )
        return (out[0], fps)


NODE_CLASS_MAPPINGS = {"FikoYTWanT2V": FikoYTWanT2V}
NODE_DISPLAY_NAME_MAPPINGS = {"FikoYTWanT2V": "FikoYT • Wan 2.2 T2V"}
