from __future__ import annotations

import asyncio
from unittest.mock import AsyncMock, patch

from app.services.feishu_async_service import _get_docx_content_async
from app.services.feishu_service import FeishuRetrievalConfig, _get_docx_content


def _config() -> FeishuRetrievalConfig:
    return FeishuRetrievalConfig(
        search_url="",
        app_id="app-id",
        app_secret="secret",
        timeout_seconds=10,
        retry_count=1,
    )


def _heading(text: str) -> dict:
    return {
        "block_type": 3,
        "heading1": {"elements": [{"text_run": {"content": text}}]},
    }


def test_docx_content_reads_all_block_pages():
    pages = [
        {"data": {"items": [_heading("第一页")], "has_more": True, "page_token": "next-page"}},
        {"data": {"items": [_heading("第二页作业")], "has_more": False, "page_token": ""}},
    ]
    with patch("app.services.feishu_service._feishu_get", side_effect=pages) as feishu_get:
        content = _get_docx_content("doc-token", _config())

    assert "第一页" in content
    assert "第二页作业" in content
    assert feishu_get.call_count == 2
    assert feishu_get.call_args_list[0].kwargs["params"] == {"page_size": 500}
    assert feishu_get.call_args_list[1].kwargs["params"] == {"page_size": 500, "page_token": "next-page"}


def test_async_docx_content_reads_all_block_pages():
    pages = [
        {"data": {"items": [_heading("第一页")], "has_more": True, "page_token": "next-page"}},
        {"data": {"items": [_heading("第二页作业")], "has_more": False, "page_token": ""}},
    ]
    feishu_get = AsyncMock(side_effect=pages)
    with patch("app.services.feishu_async_service._feishu_get_async", feishu_get):
        content = asyncio.run(_get_docx_content_async("doc-token", _config()))

    assert "第一页" in content
    assert "第二页作业" in content
    assert feishu_get.await_count == 2
    assert feishu_get.await_args_list[1].kwargs["params"] == {"page_size": 500, "page_token": "next-page"}
