"""Entities 领域层单元测试 - entities.py"""

import pytest

from packages.domain.classification import (
    AssetLibraryKind,
    ClassificationStatus,
    IngestJobStatus,
)
from packages.domain.entities import (
    Asset,
    AssetLibrary,
    AssetStatus,
    IngestJob,
    Project,
    User,
)


class TestAssetStatus:
    """AssetStatus 枚举 + _missing_ 兼容测试"""

    def test_normal_values(self):
        """正常枚举值"""
        assert AssetStatus.UPLOADING == "uploading"
        assert AssetStatus.READY == "ready"
        assert AssetStatus.PROCESSING == "processing"
        assert AssetStatus.ERROR == "error"
        assert AssetStatus.DELETED == "deleted"

    def test_missing_uploaded_maps_to_ready(self):
        """历史值 uploaded → READY"""
        assert AssetStatus("uploaded") == AssetStatus.READY

    def test_missing_success_maps_to_ready(self):
        assert AssetStatus("success") == AssetStatus.READY

    def test_missing_done_maps_to_ready(self):
        assert AssetStatus("done") == AssetStatus.READY

    def test_missing_upload_maps_to_uploading(self):
        assert AssetStatus("upload") == AssetStatus.UPLOADING

    def test_missing_failed_maps_to_error(self):
        assert AssetStatus("failed") == AssetStatus.ERROR

    def test_missing_process_maps_to_processing(self):
        assert AssetStatus("process") == AssetStatus.PROCESSING

    def test_missing_running_maps_to_processing(self):
        assert AssetStatus("running") == AssetStatus.PROCESSING

    def test_missing_unknown_defaults_to_ready(self):
        """完全未知的值兜底为 READY（不阻塞业务）"""
        assert AssetStatus("completely_unknown") == AssetStatus.READY

    def test_missing_case_insensitive(self):
        """大小写不敏感"""
        assert AssetStatus("UPLOADED") == AssetStatus.READY
        assert AssetStatus("Success") == AssetStatus.READY

    def test_missing_with_spaces(self):
        """带空格也能处理"""
        assert AssetStatus("  uploaded  ") == AssetStatus.READY

    def test_missing_non_string_defaults_to_ready(self):
        """非字符串输入兜底为 READY"""
        assert AssetStatus(None) == AssetStatus.READY
        assert AssetStatus(123) == AssetStatus.READY


class TestUser:
    """User 实体测试"""

    def test_create_minimal(self):
        """最小化创建"""
        user = User(
            id="user-1",
            email="test@example.com",
            display_name="Test User",
        )
        assert user.id == "user-1"
        assert user.email == "test@example.com"
        assert user.display_name == "Test User"
        assert user.username == ""
        assert user.email_verified is False
        assert user.subscription_plan == "free"
        assert user.is_admin is False
        assert user.created_at is not None

    def test_create_with_all_fields(self):
        """全字段创建"""
        user = User(
            id="user-1",
            email="test@example.com",
            display_name="Test",
            username="testuser",
            password_hash="hash123",
            email_verified=True,
            subscription_plan="pro",
            is_admin=True,
            wechat_openid="wx_openid",
            phone="13800138000",
            phone_verified=True,
        )
        assert user.username == "testuser"
        assert user.subscription_plan == "pro"
        assert user.is_admin is True
        assert user.wechat_openid == "wx_openid"
        assert user.phone == "13800138000"
        assert user.phone_verified is True

    def test_default_subscription_is_free(self):
        user = User(id="u1", email="a@b.com", display_name="A")
        assert user.subscription_plan == "free"

    def test_default_max_projects(self):
        user = User(id="u1", email="a@b.com", display_name="A")
        assert user.max_projects == 3

    def test_default_storage(self):
        user = User(id="u1", email="a@b.com", display_name="A")
        assert user.max_storage_gb == 10
        assert user.used_storage_gb == 0.0


class TestProject:
    """Project 实体测试"""

    def test_create_minimal(self):
        project = Project.create(
            owner_user_id="user-1",
            name="My Project",
        )
        assert project.id
        assert len(project.id) == 32
        assert project.owner_user_id == "user-1"
        assert project.name == "My Project"
        assert project.description == ""
        assert project.shared_users == []
        assert project.created_at is not None

    def test_create_with_description(self):
        project = Project.create(
            owner_user_id="user-1",
            name="Test",
            description="A test project",
        )
        assert project.description == "A test project"

    def test_create_empty_name_raises(self):
        with pytest.raises(ValueError, match="项目名称不能为空"):
            Project.create(owner_user_id="user-1", name="")

    def test_create_whitespace_name_raises(self):
        with pytest.raises(ValueError, match="项目名称不能为空"):
            Project.create(owner_user_id="user-1", name="   ")

    def test_create_name_stripped(self):
        project = Project.create(owner_user_id="user-1", name="  My Project  ")
        assert project.name == "My Project"

    def test_create_description_stripped(self):
        project = Project.create(
            owner_user_id="user-1",
            name="Test",
            description="  desc  ",
        )
        assert project.description == "desc"

    def test_is_owner_true(self):
        project = Project.create(owner_user_id="user-1", name="Test")
        assert project.is_owner("user-1") is True

    def test_is_owner_false(self):
        project = Project.create(owner_user_id="user-1", name="Test")
        assert project.is_owner("user-2") is False

    def test_is_shared_with_true(self):
        project = Project.create(owner_user_id="user-1", name="Test")
        project.shared_users = ["user-2", "user-3"]
        assert project.is_shared_with("user-2") is True

    def test_is_shared_with_false(self):
        project = Project.create(owner_user_id="user-1", name="Test")
        assert project.is_shared_with("user-2") is False

    def test_can_access_owner(self):
        project = Project.create(owner_user_id="user-1", name="Test")
        assert project.can_access("user-1") is True

    def test_can_access_shared_user(self):
        project = Project.create(owner_user_id="user-1", name="Test")
        project.shared_users = ["user-2"]
        assert project.can_access("user-2") is True

    def test_can_access_stranger(self):
        project = Project.create(owner_user_id="user-1", name="Test")
        assert project.can_access("user-3") is False


class TestAssetLibrary:
    """AssetLibrary 实体测试"""

    def test_create_video_library(self):
        library = AssetLibrary.create(
            project_id="proj-1",
            name="视频素材",
            kind=AssetLibraryKind.VIDEO,
        )
        assert library.id
        assert len(library.id) == 32
        assert library.project_id == "proj-1"
        assert library.name == "视频素材"
        assert library.kind == AssetLibraryKind.VIDEO
        assert library.asset_count == 0
        assert library.total_size == 0
        assert library.created_at is not None

    def test_create_audio_library(self):
        library = AssetLibrary.create(
            project_id="proj-1",
            name="音频素材",
            kind=AssetLibraryKind.VOICE,
        )
        assert library.kind == AssetLibraryKind.VOICE

    def test_create_image_library(self):
        library = AssetLibrary.create(
            project_id="proj-1",
            name="图片素材",
            kind=AssetLibraryKind.IMAGE,
        )
        assert library.kind == AssetLibraryKind.IMAGE

    def test_create_empty_name_raises(self):
        with pytest.raises(ValueError, match="素材库名称不能为空"):
            AssetLibrary.create(
                project_id="proj-1",
                name="",
                kind=AssetLibraryKind.VIDEO,
            )

    def test_create_whitespace_name_raises(self):
        with pytest.raises(ValueError, match="素材库名称不能为空"):
            AssetLibrary.create(
                project_id="proj-1",
                name="   ",
                kind=AssetLibraryKind.VIDEO,
            )

    def test_create_name_stripped(self):
        library = AssetLibrary.create(
            project_id="proj-1",
            name="  视频库  ",
            kind=AssetLibraryKind.VIDEO,
        )
        assert library.name == "视频库"


class TestAsset:
    """Asset 实体测试"""

    def test_create_minimal(self):
        asset = Asset.create(
            project_id="proj-1",
            library_id="lib-1",
            name="test.mp4",
            storage_key="assets/test.mp4",
            mime_type="video/mp4",
        )
        assert asset.id
        assert len(asset.id) == 32
        assert asset.project_id == "proj-1"
        assert asset.library_id == "lib-1"
        assert asset.name == "test.mp4"
        assert asset.storage_key == "assets/test.mp4"
        assert asset.mime_type == "video/mp4"
        assert asset.status == AssetStatus.UPLOADING
        assert asset.classification_status == ClassificationStatus.PENDING
        assert asset.tag_ids == []
        assert asset.metadata == {}

    def test_create_empty_name_raises(self):
        with pytest.raises(ValueError, match="素材名称不能为空"):
            Asset.create(
                project_id="p1",
                library_id="l1",
                name="",
                storage_key="k",
                mime_type="video/mp4",
            )

    def test_create_empty_storage_key_raises(self):
        with pytest.raises(ValueError, match="storage_key 不能为空"):
            Asset.create(
                project_id="p1",
                library_id="l1",
                name="test",
                storage_key="  ",
                mime_type="video/mp4",
            )

    def test_create_empty_mime_type_raises(self):
        with pytest.raises(ValueError, match="mime_type 不能为空"):
            Asset.create(
                project_id="p1",
                library_id="l1",
                name="test",
                storage_key="k",
                mime_type="  ",
            )

    def test_file_type_video(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        assert asset.file_type == "video"

    def test_file_type_audio(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp3",
            storage_key="k",
            mime_type="audio/mpeg",
        )
        assert asset.file_type == "audio"

    def test_file_type_image(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.jpg",
            storage_key="k",
            mime_type="image/jpeg",
        )
        assert asset.file_type == "image"

    def test_file_type_no_slash(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test",
            storage_key="k",
            mime_type="unknown",
        )
        assert asset.file_type == "unknown"

    def test_add_tag(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        asset.add_tag("tag-1")
        assert "tag-1" in asset.tag_ids
        assert len(asset.tag_ids) == 1

    def test_add_tag_deduplicates(self):
        """重复添加标签自动去重"""
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        asset.add_tag("tag-1")
        asset.add_tag("tag-1")
        assert len(asset.tag_ids) == 1

    def test_add_empty_tag_raises(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        with pytest.raises(ValueError, match="标签 ID 不能为空"):
            asset.add_tag("")

    def test_add_tag_strips(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        asset.add_tag("  tag-1  ")
        assert asset.tag_ids == ["tag-1"]

    def test_remove_tag(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        asset.add_tag("tag-1")
        asset.add_tag("tag-2")
        asset.remove_tag("tag-1")
        assert "tag-1" not in asset.tag_ids
        assert "tag-2" in asset.tag_ids
        assert len(asset.tag_ids) == 1

    def test_remove_nonexistent_tag_no_error(self):
        """删除不存在的标签不报错（幂等）"""
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        asset.remove_tag("nonexistent")  # 不抛异常
        assert len(asset.tag_ids) == 0

    def test_add_tag_updates_updated_at(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        old_updated = asset.updated_at
        import time

        time.sleep(0.001)
        asset.add_tag("tag-1")
        assert asset.updated_at >= old_updated

    def test_remove_tag_updates_updated_at(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
        )
        asset.add_tag("tag-1")
        old_updated = asset.updated_at
        import time

        time.sleep(0.001)
        asset.remove_tag("tag-1")
        assert asset.updated_at >= old_updated

    def test_create_with_file_size(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
            file_size=1024,
        )
        assert asset.file_size == 1024

    def test_create_with_video_properties(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
            duration=60.5,
            width=1920,
            height=1080,
            fps=30.0,
            codec="h264",
        )
        assert asset.duration == 60.5
        assert asset.width == 1920
        assert asset.height == 1080
        assert asset.fps == 30.0
        assert asset.codec == "h264"

    def test_create_with_metadata(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
            metadata={"source": "upload"},
        )
        assert asset.metadata == {"source": "upload"}

    def test_create_none_metadata_defaults_to_empty_dict(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="test.mp4",
            storage_key="k",
            mime_type="video/mp4",
            metadata=None,
        )
        assert asset.metadata == {}

    def test_name_stripped(self):
        asset = Asset.create(
            project_id="p1",
            library_id="l1",
            name="  test.mp4  ",
            storage_key="k",
            mime_type="video/mp4",
        )
        assert asset.name == "test.mp4"


class TestIngestJob:
    """IngestJob 实体测试"""

    def test_create_minimal(self):
        job = IngestJob.create(
            project_id="proj-1",
            library_id="lib-1",
            storage_key="assets/test.mp4",
        )
        assert job.id
        assert len(job.id) == 32
        assert job.project_id == "proj-1"
        assert job.library_id == "lib-1"
        assert job.storage_key == "assets/test.mp4"
        assert job.status == IngestJobStatus.PENDING
        assert job.error_message == ""
        assert job.result_asset_id == ""
        assert job.created_at is not None

    def test_create_with_file_hash(self):
        job = IngestJob.create(
            project_id="proj-1",
            library_id="lib-1",
            storage_key="assets/test.mp4",
            file_hash="abc123",
        )
        assert job.file_hash == "abc123"

    def test_create_empty_project_id_raises(self):
        with pytest.raises(ValueError, match="project_id 不能为空"):
            IngestJob.create(
                project_id="",
                library_id="lib-1",
                storage_key="k",
            )

    def test_create_empty_library_id_raises(self):
        with pytest.raises(ValueError, match="library_id 不能为空"):
            IngestJob.create(
                project_id="p1",
                library_id="",
                storage_key="k",
            )

    def test_create_empty_storage_key_raises(self):
        with pytest.raises(ValueError, match="storage_key 不能为空"):
            IngestJob.create(
                project_id="p1",
                library_id="l1",
                storage_key="",
            )

    def test_create_whitespace_project_id_raises(self):
        with pytest.raises(ValueError, match="project_id 不能为空"):
            IngestJob.create(
                project_id="   ",
                library_id="lib-1",
                storage_key="k",
            )

    def test_create_strips_fields(self):
        job = IngestJob.create(
            project_id="  proj-1  ",
            library_id="  lib-1  ",
            storage_key="  assets/test.mp4  ",
            file_hash="  hash123  ",
        )
        assert job.project_id == "proj-1"
        assert job.library_id == "lib-1"
        assert job.storage_key == "assets/test.mp4"
        assert job.file_hash == "hash123"
