import pytest

from hef.catalog import LICENSES
from tools.licensing import librivox_license, normalize_license


def test_cc_by_url_maps_and_requires_attribution():
    lic, attr = normalize_license(
        "https://creativecommons.org/licenses/by/4.0/", creator="Jane Doe"
    )
    assert lic == "cc_by" and "Jane Doe" in attr


def test_cc_by_identifier_maps():
    lic, attr = normalize_license("CC BY 4.0", creator="Sam")
    assert lic == "cc_by" and attr


def test_cc_by_nc_maps():
    lic, attr = normalize_license(
        "https://creativecommons.org/licenses/by-nc/4.0/", creator="Artist"
    )
    assert lic == "cc_by_nc" and "Artist" in attr


def test_cc_by_without_creator_still_has_nonempty_attribution():
    # validate() rejects an attribution license with empty attribution, so the
    # normalizer must always produce a non-empty string for cc_by/cc_by_nc.
    lic, attr = normalize_license("https://creativecommons.org/licenses/by/4.0/")
    assert lic == "cc_by" and attr != ""


def test_cc0_maps_with_empty_attribution():
    lic, attr = normalize_license("https://creativecommons.org/publicdomain/zero/1.0/")
    assert lic == "cc0" and attr == ""


def test_cc0_identifier():
    lic, attr = normalize_license("CC0")
    assert lic == "cc0" and attr == ""


def test_public_domain_mark():
    lic, attr = normalize_license(
        "https://creativecommons.org/publicdomain/mark/1.0/"
    )
    assert lic == "public_domain" and attr == ""


def test_no_known_copyright_is_public_domain():
    lic, attr = normalize_license("No known copyright")
    assert lic == "public_domain" and attr == ""


def test_public_domain_literal():
    lic, attr = normalize_license("public_domain")
    assert lic == "public_domain" and attr == ""


def test_unmappable_rejected():
    with pytest.raises(ValueError):
        normalize_license("All Rights Reserved")


def test_empty_rejected():
    with pytest.raises(ValueError):
        normalize_license("")


def test_librivox_license_helper():
    lic, attr = librivox_license()
    assert lic == "public_domain" and attr == ""


def test_all_outputs_in_vocab():
    samples = [
        "https://creativecommons.org/licenses/by/4.0/",
        "https://creativecommons.org/licenses/by-nc/4.0/",
        "CC0",
        "public domain",
    ]
    for raw in samples:
        lic, _ = normalize_license(raw, creator="x")
        assert lic in LICENSES
