"""Tests de las partes puras de comfyui_fetch_output_video.

Cubren la localizacion del output de video/animacion (la logica con sustancia)
sin tocar red ni GPU: clasificacion por extension, fallback por campo "format",
prioridad de claves de video, y ausencia de video. La descarga real via /view se
valida por integracion contra el server (ver report 0110).
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from comfyui_fetch_output_video import _find_video_output, _is_video_item


def test_is_video_item_por_extension():
    assert _is_video_item({"filename": "a.mp4"})
    assert _is_video_item({"filename": "a.webp"})
    assert _is_video_item({"filename": "a.webm"})
    assert _is_video_item({"filename": "a.gif"})
    assert not _is_video_item({"filename": "a.png"})
    assert not _is_video_item({"filename": "a.glb"})


def test_is_video_item_fallback_format():
    # VHS_VideoCombine / SaveVideo a veces no dan extension clara pero anotan format.
    assert _is_video_item({"filename": "clip", "format": "video/h264-mp4"})
    assert not _is_video_item({"filename": "clip", "format": "image/png"})


def test_find_saveanimatedwebp_bajo_images():
    # SVD / SaveAnimatedWEBP exponen el .webp bajo la clave "images".
    outs = {"30": {"images": [{"filename": "svd_00001_.webp", "subfolder": "", "type": "output"}]}}
    got = _find_video_output(outs)
    assert got is not None and got["filename"] == "svd_00001_.webp"


def test_find_savevideo_mp4_bajo_images():
    outs = {"79": {"images": [{"filename": "video_00003_.mp4", "subfolder": "", "type": "output"}]}}
    assert _find_video_output(outs)["filename"] == "video_00003_.mp4"


def test_find_vhs_bajo_gifs():
    # VHS_VideoCombine expone el resultado bajo "gifs".
    outs = {"9": {"gifs": [{"filename": "out.webm", "subfolder": "sub", "type": "output"}]}}
    got = _find_video_output(outs)
    assert got["filename"] == "out.webm" and got["subfolder"] == "sub"


def test_find_prioriza_clave_video_sobre_images():
    # Si hay una clave preferente de video y tambien una imagen suelta, gana el video.
    outs = {
        "1": {"images": [{"filename": "preview.png", "subfolder": "", "type": "output"}]},
        "2": {"videos": [{"filename": "final.mp4", "subfolder": "", "type": "output"}]},
    }
    assert _find_video_output(outs)["filename"] == "final.mp4"


def test_find_sin_video_devuelve_none():
    outs = {"1": {"images": [{"filename": "foo.png", "subfolder": "", "type": "output"}]}}
    assert _find_video_output(outs) is None
    assert _find_video_output({}) is None


if __name__ == "__main__":
    import pytest

    raise SystemExit(pytest.main([__file__, "-v"]))
