"""企业微信主动消息推送"""
import httpx
import time
from typing import Optional, Dict
from src.config import get_settings


class WeChatPushClient:
    """企业微信推送客户端"""

    def __init__(self):
        settings = get_settings()
        self.corp_id = getattr(settings, 'WECHAT_CORP_ID', '')
        self.agent_id = getattr(settings, 'WECHAT_AGENT_ID', '')
        self.secret = getattr(settings, 'WECHAT_SECRET', '')
        self._access_token: Optional[str] = None
        self._token_expires_at = 0

    async def _get_access_token(self) -> str:
        """获取访问令牌（带缓存）"""
        if self._access_token and time.time() < self._token_expires_at:
            return self._access_token

        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        params = {
            'corpid': self.corp_id,
            'corpsecret': self.secret,
        }

        async with httpx.AsyncClient() as client:
            response = await client.get(url, params=params)
            data = response.json()

            if data.get('errcode') == 0:
                self._access_token = data['access_token']
                self._token_expires_at = time.time() + data.get('expires_in', 7200) - 300
                return self._access_token
            else:
                raise Exception(f"Failed to get access token: {data}")

    async def send_text_message(self, user_id: str, content: str) -> Dict:
        """发送文本消息给指定用户"""
        access_token = await self._get_access_token()
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"

        payload = {
            'touser': user_id,
            'msgtype': 'text',
            'agentid': self.agent_id,
            'text': {'content': content},
            'safe': 0,
        }

        async with httpx.AsyncClient() as client:
            response = await client.post(url, json=payload)
            return response.json()

    async def send_markdown_message(self, user_id: str, content: str) -> Dict:
        """发送Markdown消息给指定用户"""
        access_token = await self._get_access_token()
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"

        payload = {
            'touser': user_id,
            'msgtype': 'markdown',
            'agentid': self.agent_id,
            'markdown': {'content': content},
        }

        async with httpx.AsyncClient() as client:
            response = await client.post(url, json=payload)
            return response.json()


async def send_task_completion_notification(user_id: str, task_id: str, result_summary: str):
    """发送任务完成通知"""
    client = WeChatPushClient()
    content = f"""## 任务完成通知

{result_summary}

> 任务ID: {task_id}
> 点击查看详细结果
"""
    return await client.send_markdown_message(user_id, content)
