import asyncio
import logging

from app.workers.platforms.base import BasePlatformAdapter
from app.workers.platforms.search_engine import fetch_search_content

logger = logging.getLogger(__name__)


class TiangongAdapter(BasePlatformAdapter):
    """天工AI平台适配器（搜索引擎模式）"""

    platform_name = "tiangong"
    platform_url = "https://www.tiangong.cn/"

    async def query(self, keyword: str) -> str:
        """在天工AI查询关键词，返回原始响应文本"""
        last_error = None
        for attempt in range(3):  # 最多重试2次，共3次尝试
            try:
                return await self._do_query(keyword)
            except Exception as e:
                last_error = e
                logger.warning(f"天工AI查询第 {attempt + 1} 次尝试失败: {e}")
                if attempt < 2:
                    await asyncio.sleep(2 ** attempt)  # 指数退避

        logger.error(f"天工AI查询最终失败: {last_error}")
        raise last_error

    async def _do_query(self, keyword: str) -> str:
        """单次查询实现：通过搜索引擎获取与关键词相关的真实内容"""
        return await fetch_search_content(self.platform_name, keyword)

    async def close(self):
        """清理资源（搜索引擎模式无额外资源需要释放）"""
        pass
