import pytest

from packages.domain import Asset


def test_add_tag_to_asset():
    """测试添加标签 ID 到 Asset。"""
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name="video.mp4",
        storage_key="uploads/abc/video.mp4",
        mime_type="video/mp4",
    )

    asset.add_tag("tag-1")
    asset.add_tag("tag-2")

    assert len(asset.tag_ids) == 2
    assert "tag-1" in asset.tag_ids
    assert "tag-2" in asset.tag_ids


def test_add_duplicate_tag_should_ignore():
    """测试添加重复标签 ID 应自动去重。"""
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name="video.mp4",
        storage_key="uploads/abc/video.mp4",
        mime_type="video/mp4",
    )

    asset.add_tag("tag-1")
    asset.add_tag("tag-1")  # 重复

    assert len(asset.tag_ids) == 1
    assert asset.tag_ids.count("tag-1") == 1


def test_add_empty_tag_should_fail():
    """测试添加空标签 ID 应失败。"""
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name="video.mp4",
        storage_key="uploads/abc/video.mp4",
        mime_type="video/mp4",
    )

    with pytest.raises(ValueError, match="标签 ID 不能为空"):
        asset.add_tag("")

    with pytest.raises(ValueError, match="标签 ID 不能为空"):
        asset.add_tag("   ")  # 仅空格


def test_remove_tag_from_asset():
    """测试从 Asset 删除标签 ID。"""
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name="video.mp4",
        storage_key="uploads/abc/video.mp4",
        mime_type="video/mp4",
    )

    asset.add_tag("tag-1")
    asset.add_tag("tag-2")

    asset.remove_tag("tag-1")

    assert len(asset.tag_ids) == 1
    assert "tag-1" not in asset.tag_ids
    assert "tag-2" in asset.tag_ids


def test_remove_nonexistent_tag_should_be_idempotent():
    """测试删除不存在的标签 ID 应幂等（不报错）。"""
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name="video.mp4",
        storage_key="uploads/abc/video.mp4",
        mime_type="video/mp4",
    )

    asset.add_tag("tag-1")

    # 删除不存在的标签 ID，不应报错
    asset.remove_tag("nonexistent-tag")

    assert len(asset.tag_ids) == 1
    assert "tag-1" in asset.tag_ids
