import aiohttp
import marshmallow
import pytest

from funkwhale_cli import api


async def test_fetch_nodeinfo(session, responses):
    domain = "test.domain"
    well_known_payload = {
        "links": [
            {
                "rel": "http://nodeinfo.diaspora.software/ns/schema/2.0",
                "href": "https://test.domain/nodeinfo/2.0/",
            }
        ]
    }
    payload = {"hello": "world"}
    responses.get(
        "https://test.domain/.well-known/nodeinfo", payload=well_known_payload
    )
    responses.get("https://test.domain/nodeinfo/2.0/", payload=payload)
    result = await api.fetch_nodeinfo(session, domain)
    assert result == payload


def test_clean_nodeinfo():
    payload = {
        "version": "2.0",
        "software": {"name": "funkwhale", "version": "0.18-dev+git.b575999e"},
        "openRegistrations": False,
        "usage": {"users": {"total": 78, "activeHalfyear": 42, "activeMonth": 23}},
        "metadata": {
            "private": False,
            "nodeName": "Test Domain",
            "library": {
                "federationEnabled": True,
                "federationNeedsApproval": True,
                "anonymousCanListen": True,
                "tracks": {"total": 98552},
                "artists": {"total": 9831},
                "albums": {"total": 10872},
                "music": {"hours": 7650.678055555555},
            },
            "usage": {
                "favorites": {"tracks": {"total": 1683}},
                "listenings": {"total": 50294},
            },
        },
    }
    expected = {
        "software": {
            "name": "funkwhale",
            "version": {
                "major": 0,
                "minor": 18,
                "patch": 0,
                "prerelease": "dev",
                "build": "git.b575999e",
            },
        },
        "openRegistrations": False,
        "usage": {"users": {"total": 78, "activeHalfyear": 42, "activeMonth": 23}},
        "metadata": {
            "private": False,
            "nodeName": "Test Domain",
            "library": {
                "federationEnabled": True,
                "anonymousCanListen": True,
                "tracks": {"total": 98552},
                "artists": {"total": 9831},
                "albums": {"total": 10872},
                "music": {"hours": 7650},
            },
            "usage": {"listenings": {"total": 50294}},
        },
    }
    result = api.clean_nodeinfo(payload)
    assert result == expected


def test_clean_nodeinfo_raises_on_validation_failure():
    payload = {}
    with pytest.raises(marshmallow.ValidationError):
        api.clean_nodeinfo({})