# retoor <retoor@molodetz.nl>

from PIL import Image

from devplacepy.routers.tools.isslop import MEDIA_NAME_PATTERN
from devplacepy.services.jobs.isslop.agent.vision import make_thumbnail


def test_make_thumbnail_preserves_aspect_ratio(tmp_path):
    source = tmp_path / "wide.png"
    Image.new("RGB", (1600, 400), (255, 0, 0)).save(source)
    name = make_thumbnail(source, tmp_path / "media", "assets/wide.png")
    assert name is not None
    assert MEDIA_NAME_PATTERN.match(name)
    with Image.open(tmp_path / "media" / name) as thumb:
        assert thumb.format == "WEBP"
        assert thumb.width <= 480 and thumb.height <= 480
        assert abs(thumb.width / thumb.height - 4.0) < 0.05


def test_make_thumbnail_is_deterministic_per_path(tmp_path):
    source = tmp_path / "icon.png"
    Image.new("RGBA", (256, 256), (0, 0, 255, 128)).save(source)
    first = make_thumbnail(source, tmp_path / "media", "public/icon.png")
    second = make_thumbnail(source, tmp_path / "media", "public/icon.png")
    assert first == second
    assert make_thumbnail(source, tmp_path / "media", "other/icon.png") != first


def test_make_thumbnail_fails_soft_on_unreadable(tmp_path):
    source = tmp_path / "broken.png"
    source.write_bytes(b"not an image")
    assert make_thumbnail(source, tmp_path / "media", "broken.png") is None
