"""Tests para image_save_png — guarda PNG con metadata tEXt embebida."""

import sys

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

import pytest

PIL = pytest.importorskip("PIL", reason="Pillow no instalado — skipping")

from image_save_png import image_save_png


def test_guarda_archivo_y_retorna_ruta_absoluta(tmp_path):
    """crea imagen 8x8, guarda y retorna ruta absoluta"""
    from PIL import Image

    img = Image.new("RGB", (8, 8), color=(255, 0, 0))
    dest = str(tmp_path / "test.png")
    result = image_save_png(img, dest)

    import os
    assert os.path.isfile(result), f"El archivo no existe: {result}"
    assert os.path.isabs(result), f"La ruta no es absoluta: {result}"


def test_metadata_embebida_en_chunks_text(tmp_path):
    """metadata se embebe en chunks tEXt y se puede releer con Image.text"""
    from PIL import Image

    img = Image.new("RGB", (8, 8), color=(0, 128, 0))
    dest = str(tmp_path / "with_meta.png")
    meta = {"prompt": "hi", "seed": "42"}
    image_save_png(img, dest, metadata=meta)

    reopened = Image.open(dest)
    text_data = reopened.text  # dict de chunks tEXt del PNG
    assert "prompt" in text_data, f"Falta clave 'prompt' en PNG text chunks: {text_data}"
    assert "seed" in text_data, f"Falta clave 'seed' en PNG text chunks: {text_data}"
    assert text_data["prompt"] == "hi"
    assert text_data["seed"] == "42"


def test_sin_metadata_no_falla(tmp_path):
    """sin metadata el PNG se guarda igualmente"""
    from PIL import Image

    img = Image.new("RGB", (8, 8))
    dest = str(tmp_path / "no_meta.png")
    result = image_save_png(img, dest, metadata=None)

    import os
    assert os.path.isfile(result)


def test_crea_directorio_padre(tmp_path):
    """crea directorio padre si no existe"""
    from PIL import Image
    import os

    img = Image.new("RGB", (8, 8))
    dest = str(tmp_path / "subdir" / "deep" / "image.png")
    result = image_save_png(img, dest)
    assert os.path.isfile(result)


def test_metadata_valores_numericos_se_convierten_a_str(tmp_path):
    """valores numericos en metadata se convierten a str automaticamente"""
    from PIL import Image

    img = Image.new("RGB", (8, 8))
    dest = str(tmp_path / "numeric.png")
    meta = {"steps": 30, "cfg_scale": 7.5}
    image_save_png(img, dest, metadata=meta)

    reopened = Image.open(dest)
    text_data = reopened.text
    assert "steps" in text_data
    assert "cfg_scale" in text_data
    assert text_data["steps"] == "30"
    assert text_data["cfg_scale"] == "7.5"
