"""WeCom access token management, message sending, and Markdown stripping."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_api.ipynb.

# %% auto #0
__all__ = ['strip_md', 'get_access_token', 'send_text']

# %% ../nbs/02_api.ipynb #c7ce0335
import re, time
import httpx
from .config import CORP_ID, SECRET, AGENT_ID, CHUNK_SIZE, TOKEN_BUFFER

# %% ../nbs/02_api.ipynb #62794d74
def strip_md(
    s: str  # Text potentially containing Markdown syntax
) -> str:
    "Strip common Markdown so text reads cleanly in WeChat."
    s = re.sub(r'```[\s\S]*?```', '', s)
    for pat, repl in [
        (r'`([^`]+)`',              r'\1'),  # inline code
        (r'\*+(.+?)\*+',            r'\1'),  # bold / italic
        (r'^#{1,6}\s+',             ''   ),  # headings
        (r'^\s*[-*+]\s+',           '• ' ),  # bullets
        (r'\[([^\]]+)\]\([^\)]+\)', r'\1'),  # links
    ]:
        s = re.sub(pat, repl, s, flags=re.MULTILINE)
    return s.strip()

# %% ../nbs/02_api.ipynb #02ca9445
_token_cache = {'token': '', 'expires': 0}

async def get_access_token() -> str:
    "Return a valid WeCom access token, refreshing from the API 5 min before expiry."
    now = time.time()
    if _token_cache['token'] and now < _token_cache['expires']:
        return _token_cache['token']
    async with httpx.AsyncClient() as c:
        r = await c.get('https://qyapi.weixin.qq.com/cgi-bin/gettoken',
                        params={'corpid': CORP_ID, 'corpsecret': SECRET})
    d = r.json()
    if d.get('errcode', 0) != 0: raise Exception(f"获取 token 失败: {d}")
    _token_cache.update(token=d['access_token'], expires=now + d['expires_in'] - TOKEN_BUFFER)
    return _token_cache['token']

# %% ../nbs/02_api.ipynb #ac66af0f
async def send_text(
    user_id: str,  # WeCom recipient user ID
    text: str      # Message text; Markdown is stripped automatically
):
    "Send `text` via the WeCom API, chunking into `CHUNK_SIZE`-char segments."
    token = await get_access_token()
    url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}'
    text = strip_md(text)
    async with httpx.AsyncClient() as c:
        for i in range(0, len(text), CHUNK_SIZE):
            r = await c.post(url, json={
                'touser': user_id, 'msgtype': 'text',
                'agentid': int(AGENT_ID), 'text': {'content': text[i:i+CHUNK_SIZE]}})
            if (d := r.json()).get('errcode', 0) != 0:
                import logging; logging.getLogger('wecom').info(f"⚠️ 发送失败: {d}")
