# retoor <retoor@molodetz.nl>

import requests
from devplacepy.avatar import avatar_seed, avatar_url, generate_avatar_svg
from tests.conftest import BASE_URL


def test_avatar_url_format():
    url = avatar_url("multiavatar", "testuser", 128)
    assert url == "/avatar/multiavatar/testuser?size=128"


def test_avatar_url_different_size():
    url = avatar_url("multiavatar", "testuser", 64)
    assert "size=64" in url


def test_avatar_url_contains_seed():
    url = avatar_url("multiavatar", "customuser", 128)
    assert "customuser" in url


def test_generate_avatar_svg_returns_string():
    svg = generate_avatar_svg("testuser")
    assert isinstance(svg, str)
    assert len(svg) > 100


def test_generate_avatar_svg_is_svg():
    svg = generate_avatar_svg("testuser")
    assert svg.strip().startswith("<svg")
    assert "xmlns" in svg


def test_generate_avatar_svg_deterministic():
    svg1 = generate_avatar_svg("testuser")
    svg2 = generate_avatar_svg("testuser")
    assert svg1 == svg2


def test_generate_avatar_svg_different_for_different_seeds():
    svg1 = generate_avatar_svg("alice")
    svg2 = generate_avatar_svg("bob")
    assert svg1 != svg2


def test_generate_avatar_svg_fallback_on_exception(monkeypatch):
    import importlib

    ma = importlib.import_module("multiavatar.multiavatar")

    def _boom(*args, **kwargs):
        raise RuntimeError("avatar backend down")

    monkeypatch.setattr(ma, "multiavatar", _boom)
    svg = generate_avatar_svg("testuser")
    assert svg.strip().startswith("<svg")
    assert "<rect" in svg
    assert ">T</text>" in svg


def test_generate_avatar_svg_includes_rect_for_fallback(monkeypatch):
    import importlib

    ma = importlib.import_module("multiavatar.multiavatar")

    monkeypatch.setattr(ma, "multiavatar", lambda *a, **k: None)
    svg = generate_avatar_svg("zeta")
    assert "<rect" in svg
    assert "<text" in svg


def test_avatar_url_with_different_seeds():
    url1 = avatar_url("multiavatar", "alice", 128)
    url2 = avatar_url("multiavatar", "bob", 128)
    assert url1 != url2


def test_avatar_seed_prefers_avatar_seed_field():
    assert avatar_seed({"username": "alice", "avatar_seed": "seed-xyz"}) == "seed-xyz"


def test_avatar_seed_falls_back_to_username():
    assert avatar_seed({"username": "alice"}) == "alice"


def test_avatar_seed_falls_back_when_seed_blank():
    assert avatar_seed({"username": "alice", "avatar_seed": ""}) == "alice"
    assert avatar_seed({"username": "alice", "avatar_seed": None}) == "alice"


def test_avatar_seed_none_user():
    assert avatar_seed(None) == ""


def test_avatar_seed_empty_user():
    assert avatar_seed({}) == ""


def test_generate_avatar_svg_empty_seed_uses_fallback():
    svg = generate_avatar_svg("")
    assert isinstance(svg, str)
    assert "<rect" in svg
