"""#1714 find_recent_active_by_library_and_name 严格模式测试。

file_size=0（未知）时必须返回 None（宁可漏判不可误杀）；
大小严格匹配；只命中近期 UPLOADING/PROCESSING 记录。
"""

import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "api"))

from sqlalchemy import create_engine  # noqa: E402
from sqlalchemy.orm import sessionmaker  # noqa: E402

from packages.adapters.sqlalchemy_impl.asset_repository import SQLAlchemyAssetRepository  # noqa: E402
from packages.adapters.sqlalchemy_impl.models import Base  # noqa: E402
from packages.domain import Asset, AssetStatus  # noqa: E402


def _repository():
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    session = sessionmaker(bind=engine)()
    return SQLAlchemyAssetRepository(session)


def _mk_asset(name="IMG_2285.MOV", file_size=5_000_000, status=AssetStatus.PROCESSING, minutes_ago=5):
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name=name,
        storage_key=f"uploads/x/{name}",
        mime_type="video/quicktime",
        file_size=file_size,
    )
    asset.status = status
    asset.created_at = datetime.now(timezone.utc) - timedelta(minutes=minutes_ago)
    return asset


def test_returns_none_when_file_size_zero():
    """file_size=0（大小未知）直接返回 None——不许仅凭同名 + processing 判重。"""
    repo = _repository()
    repo.create(_mk_asset(file_size=0))

    result = repo.find_recent_active_by_library_and_name(library_id="lib-1", name="IMG_2285.MOV", file_size=0)
    assert result is None


def test_matches_when_name_size_strict_equal():
    """同名 + 同大小 + processing 近期记录 → 命中。"""
    repo = _repository()
    repo.create(_mk_asset(file_size=5_000_000))

    result = repo.find_recent_active_by_library_and_name(library_id="lib-1", name="IMG_2285.MOV", file_size=5_000_000)
    assert result is not None
    assert result.name == "IMG_2285.MOV"


def test_no_match_when_same_name_but_different_size():
    """同名但大小不同 → 不命中（内容全新的视频不能误杀）。"""
    repo = _repository()
    repo.create(_mk_asset(file_size=5_000_000))

    result = repo.find_recent_active_by_library_and_name(library_id="lib-1", name="IMG_2285.MOV", file_size=9_999_999)
    assert result is None


def test_no_match_ready_history_even_with_same_size():
    """READY 历史同名素材不命中（允许再次上传同名文件）。"""
    repo = _repository()
    repo.create(_mk_asset(file_size=5_000_000, status=AssetStatus.READY))

    result = repo.find_recent_active_by_library_and_name(library_id="lib-1", name="IMG_2285.MOV", file_size=5_000_000)
    assert result is None


def test_no_match_when_window_expired():
    """超过 30 分钟窗口的活动记录不命中。"""
    repo = _repository()
    repo.create(_mk_asset(file_size=5_000_000, minutes_ago=45))

    result = repo.find_recent_active_by_library_and_name(
        library_id="lib-1", name="IMG_2285.MOV", within_minutes=30, file_size=5_000_000
    )
    assert result is None


def test_returns_none_when_name_empty():
    repo = _repository()
    result = repo.find_recent_active_by_library_and_name(library_id="lib-1", name="", file_size=100)
    assert result is None
