"""Tests para ImageGenResult — dump excluye image, meta viaja correctamente."""

import json
import sys

sys.path.insert(0, "python/functions/ml")

from image_gen_result import ImageGenResult


def _make_result(image=None, duration_ms=1234, vram_peak_mb=None, meta=None):
    if meta is None:
        meta = {
            "model": "sd15",
            "seed_used": 42,
            "sampler": "euler_a",
            "prompt": "a cat",
        }
    return ImageGenResult(
        image=image,
        meta=meta,
        duration_ms=duration_ms,
        vram_peak_mb=vram_peak_mb,
    )


def test_instancia_ok():
    """ImageGenResult crea instancia sin errores"""
    r = _make_result(duration_ms=500)
    assert r.duration_ms == 500
    assert isinstance(r.meta, dict)


def test_dump_excluye_image():
    """model_dump excluye el campo image automaticamente"""

    class FakeImage:
        """Objeto imagen simulado (no PIL real)."""
        pass

    r = _make_result(image=FakeImage(), duration_ms=800)
    d = r.model_dump()
    assert isinstance(d, dict)
    assert "image" not in d, "image no debe aparecer en model_dump()"


def test_dump_incluye_meta_duration_vram():
    """model_dump incluye meta, duration_ms y vram_peak_mb"""
    meta = {"model": "sdxl", "seed_used": 99, "sampler": "dpm++2m"}
    r = _make_result(duration_ms=2000, vram_peak_mb=6144, meta=meta)
    d = r.model_dump()
    assert "meta" in d
    assert "duration_ms" in d
    assert "vram_peak_mb" in d
    assert d["duration_ms"] == 2000
    assert d["vram_peak_mb"] == 6144


def test_meta_dict_viaja_completo():
    """meta dict se conserva completo en model_dump"""
    meta = {
        "model": "flux_dev",
        "seed_used": 777,
        "sampler": "euler",
        "custom_key": "custom_value",
        "nested": {"a": 1},
    }
    r = _make_result(meta=meta)
    d = r.model_dump()
    assert d["meta"] == meta
    assert d["meta"]["custom_key"] == "custom_value"
    assert d["meta"]["nested"] == {"a": 1}


def test_dump_json_parseable():
    """model_dump_json retorna string JSON parseable sin image"""
    meta = {"model": "sd15", "seed_used": 1}
    r = _make_result(duration_ms=100, meta=meta)
    raw = r.model_dump_json()
    assert isinstance(raw, str)
    parsed = json.loads(raw)
    assert "meta" in parsed
    assert "duration_ms" in parsed
    assert "image" not in parsed


def test_vram_peak_mb_none_serializa():
    """vram_peak_mb=None se serializa correctamente a null"""
    r = _make_result(vram_peak_mb=None)
    d = r.model_dump()
    assert d["vram_peak_mb"] is None


def test_image_none_permitido():
    """image puede ser None (generacion fallida)"""
    r = _make_result(image=None)
    assert r.image is None
    d = r.model_dump()
    assert "image" not in d
