"""
find_agent — 老年受众高潜视频发现 Agent

职责：按需求搜索抖音视频，结合内容、分享行为和双侧年龄画像进行筛选。
"""
from __future__ import annotations

import logging
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FuturesTimeoutError

from agents.find_agent.agent import create_find_agent
from agents.find_agent.async_runner import _run_coroutine, arun_find_agent
from agents.find_agent.runtime import find_agent_timeout_seconds
from supply_agent.config import Settings
from supply_agent.types import AgentResult

__all__ = ["create_find_agent", "run_find_agent"]

logger = logging.getLogger(__name__)

_PUBLISH_TIMEOUT_SECONDS = 120.0


def run_find_agent(
    user_input: str,
    *,
    run_id: str,
    settings: Settings | None = None,
    model: str | None = None,
) -> AgentResult:
    """同步运行 find_agent。

    find_agent 的搜索/详情/画像等工具均为 async，不能直接用 agent.run()；
    此函数内部会走 agent.arun()，并在结束前关闭异步 HTTP 客户端。
    """
    agent = create_find_agent(settings=settings, model=model)
    result = _run_coroutine(
        arun_find_agent(
            agent,
            user_input,
            run_id=run_id,
            timeout_seconds=find_agent_timeout_seconds(),
        )
    )
    try:
        with ThreadPoolExecutor(max_workers=1) as publish_executor:
            publish_future = publish_executor.submit(agent._finish_run, result)
            publish_future.result(timeout=_PUBLISH_TIMEOUT_SECONDS)
    except FuturesTimeoutError:
        logger.error(
            "find_agent publish timed out after %.0fs; continuing without blocking worker",
            _PUBLISH_TIMEOUT_SECONDS,
        )
    except Exception:
        logger.exception("find_agent publish failed")
    return result
