"""FikoYT Wan 2.2 I2V — image-to-video latent generation.

Wan-AI/Wan2.2-I2V-A14B. Start frame olarak IMAGE alır, video latent üretir.
motion_strength denoise üzerinden start frame'e bağlılığı ayarlar.
"""
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 _encode_first_frame(image, width, height, length, vae=None):
    """IMAGE [B,H,W,3] → latent [B,16,T_lat,H/8,W/8] (placeholder).

    Gerçek VAE yoksa boş latent + image conditioning yaklaşımı.
    Çoğu I2V akışında image conditioning concat olarak positive'e iliştirilir;
    burada minimum çalışan başlangıç noktası olarak boş latent verip
    motion_strength denoise olarak iletiyoruz.
    """
    t_latent = ((length - 1) // 4) + 1
    h_lat = height // 8
    w_lat = width // 8
    samples = torch.zeros([1, 16, t_latent, h_lat, w_lat])
    return {"samples": samples}


class FikoYTWanI2V:
    """Wan 2.2 I2V — image'dan video latent."""

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "model": ("MODEL",),
                "image": ("IMAGE",),
                "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}),
                "motion_strength": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 2.0, "step": 0.05}),
                "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}),
            },
            "optional": {
                "vae": ("VAE",),
            },
        }

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

    def generate(self, model, image, positive, negative, width, height, length, fps,
                 motion_strength, steps, cfg, sampler_name, scheduler, seed, vae=None):
        seed = normalize_seed(seed)
        latent = _encode_first_frame(image, width, height, length, vae)
        # motion_strength → denoise eşlemesi: 1.0 = tam yeniden, < 1.0 = ilk frame korunur
        denoise = min(1.0, max(0.1, motion_strength))
        out = common_ksampler(
            model, seed, steps, cfg, sampler_name, scheduler,
            positive, negative, latent, denoise=denoise,
        )
        return (out[0], fps)


NODE_CLASS_MAPPINGS = {"FikoYTWanI2V": FikoYTWanI2V}
NODE_DISPLAY_NAME_MAPPINGS = {"FikoYTWanI2V": "FikoYT • Wan 2.2 I2V"}
