"""Tests de los helpers puros de comfyui_fetch_civitai_image_meta.

No tocan la red: validan el parseo de id, la interpretación de NSFW y la
extracción del workflow embebido. La función completa (impura) se valida en vivo
contra Civitai en el report 0127.
"""
import os
import sys

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

from comfyui_fetch_civitai_image_meta import (  # noqa: E402
    _extract_comfy_workflow,
    _is_nsfw,
    _parse_image_id,
)


def test_parse_image_id_acepta_int_str_url():
    assert _parse_image_id(23526611) == (23526611, "")
    assert _parse_image_id("23526611") == (23526611, "")
    assert _parse_image_id("https://civitai.com/images/9078035?x=1") == (9078035, "")
    assert _parse_image_id("/images/777") == (777, "")


def test_parse_image_id_rechaza_invalidos():
    for bad in ("not_an_id", -5, 0, True, 3.5, None):
        iid, err = _parse_image_id(bad)
        assert iid == 0 and err, f"deberia rechazar {bad!r}"


def test_is_nsfw_niveles():
    for sfw in (None, "None", "", 0, 1, "Safe"):
        assert _is_nsfw(sfw) is False, f"{sfw!r} deberia ser SFW"
    for nsfw in (2, 4, 16, "Mature", "X", "Soft"):
        assert _is_nsfw(nsfw) is True, f"{nsfw!r} deberia ser NSFW"


def test_extract_comfy_workflow_embebido_y_ausente():
    # meta con un comfy embebido (string JSON {prompt: API format})
    api = {"3": {"class_type": "KSampler", "inputs": {}}}
    import json
    meta_ok = {"comfy": json.dumps({"prompt": api})}
    assert _extract_comfy_workflow(meta_ok) == api
    # meta sin comfy -> {}
    assert _extract_comfy_workflow({"prompt": "hola"}) == {}
    # comfy ilegible -> {} (no crashea)
    assert _extract_comfy_workflow({"comfy": "no es json {"}) == {}


if __name__ == "__main__":
    test_parse_image_id_acepta_int_str_url()
    test_parse_image_id_rechaza_invalidos()
    test_is_nsfw_niveles()
    test_extract_comfy_workflow_embebido_y_ausente()
    print("OK")
