"""
Telegram 通知模块
- tg_send()       : 发送消息（自动分段 4000 字符，失败重试3次）
- tg_send_photo() : 发送图片（bytes），失败重试3次
- tg_get_updates(): 拉取 Bot 收到的消息
"""

import time
import logging
from config import TG_TOKEN, TG_CHAT
from exchange.http import http_get, http_post

logger = logging.getLogger("MyTrader")

_TG_URL = f"https://api.telegram.org/bot{TG_TOKEN}"


def tg_send(text, parse_mode=None):
    """推送文字消息，超长自动分段，失败自动重试3次。"""
    for chunk in [text[i:i + 4000] for i in range(0, len(text), 4000)]:
        payload = {"chat_id": TG_CHAT, "text": chunk}
        if parse_mode:
            payload["parse_mode"] = parse_mode
        for attempt in range(3):
            try:
                resp = http_post(f"{_TG_URL}/sendMessage", json=payload, timeout=12)
                if not resp.json().get("ok"):
                    logger.warning(f"[TG] sendMessage失败: {resp.text[:200]}")
                break
            except Exception as e:
                if attempt < 2:
                    time.sleep(2 * (attempt + 1))
                else:
                    logger.warning(f"[TG] 发送失败(已重试3次): {e}")


def tg_send_photo(photo_bytes: bytes, caption: str = "") -> bool:
    """发送图片（PNG/JPG bytes），失败重试3次，返回是否成功。"""
    if not photo_bytes:
        return False
    for attempt in range(3):
        try:
            resp = http_post(
                f"{_TG_URL}/sendPhoto",
                data={"chat_id": TG_CHAT, "caption": caption[:1024]},
                files={"photo": ("chart.png", photo_bytes, "image/png")},
                timeout=20,
            )
            if resp.json().get("ok"):
                return True
            logger.warning(f"[TG] sendPhoto失败: {resp.text[:200]}")
            return False
        except Exception as e:
            if attempt < 2:
                time.sleep(2 * (attempt + 1))
            else:
                logger.warning(f"[TG] 图片发送失败(已重试3次): {e}")
    return False


def tg_get_updates(offset=0):
    """拉取 Telegram 消息更新列表。"""
    try:
        r = http_get(f"{_TG_URL}/getUpdates",
                     params={"offset": offset, "timeout": 1}, timeout=8)
        return r.json().get("result", [])
    except Exception as e:
        logger.debug(f"[TG] getUpdates失败: {e}")
        return []
