import sys
import unittest
from pathlib import Path
from unittest.mock import patch


_HERE = Path(__file__).parent
sys.path.insert(0, str(_HERE))

from tools.video_recall import LandingVideo, fetch_landing_videos_for_account  # noqa: E402


def _video(video_id: int) -> LandingVideo:
    return LandingVideo(
        video_id=video_id,
        title=f"video-{video_id}",
        cover_url="",
        video_url="",
        score=0.0,
        rov=0.0,
        sim=0.0,
        visit_uv=0,
        category="",
        standard_element="",
        category_name="",
        demand_content_title="",
        demand_content_topic="",
        demand_content_id="",
        demand_type="",
        point_type="",
        dimension="",
        experiment_id=f"exp-{video_id}",
    )


class VideoRecallPaginationTest(unittest.TestCase):
    def test_fetch_for_account_reads_up_to_three_pages_and_dedupes(self):
        calls = []

        def fake_fetch(*, crowd_package, page_size, page_num=1, source, **kwargs):
            calls.append((crowd_package, page_size, page_num, source))
            pages = {
                1: [_video(1), _video(2)],
                2: [_video(2), _video(3)],
                3: [_video(4)],
            }
            return pages.get(page_num, [])

        with patch("tools.video_recall.get_account_crowd_package", return_value="回流330以上人群"), \
            patch("tools.video_recall.fetch_landing_videos", side_effect=fake_fetch):
            videos = fetch_landing_videos_for_account(
                86197363,
                page_size=2,
                max_pages=3,
                source="prior",
                enable_hot_fallback=False,
            )

        self.assertEqual([1, 2, 3, 4], [v.video_id for v in videos])
        self.assertEqual(
            [
                ("R_330+", 2, 1, "prior"),
                ("R_330+", 2, 2, "prior"),
                ("R_330+", 2, 3, "prior"),
            ],
            calls,
        )


if __name__ == "__main__":
    unittest.main()
