"""Minimal Telegram Bot API client (stdlib only)."""
import html
import json
import os
import time
import urllib.error
import urllib.request

TOKEN = os.environ.get("BOT_TOKEN", "").strip()
API = "https://api.telegram.org/bot%s/" % TOKEN


def esc(s):
    return html.escape(str(s or ""))


def call(method, http_timeout=30, **params):
    data = json.dumps(params).encode("utf-8")
    req = urllib.request.Request(API + method, data=data,
                                 headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=http_timeout) as r:
            return json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        try:
            body = json.loads(e.read().decode("utf-8"))
        except Exception:
            body = {"ok": False, "description": "HTTP %s" % e.code}
        return body
    except Exception as e:
        return {"ok": False, "description": str(e)}


def _retry(method, **params):
    res = call(method, **params)
    if res.get("ok"):
        return res
    desc = str(res.get("description", ""))
    if "retry after" in desc.lower():
        wait = 3
        try:
            wait = int(desc.split("retry after")[1].strip().split()[0])
        except Exception:
            pass
        time.sleep(min(wait, 30))
        return call(method, **params)
    return res


def send(chat_id, text, kb=None, preview=False, reply_to=None):
    p = {"chat_id": chat_id, "text": text, "parse_mode": "HTML",
         "disable_web_page_preview": not preview}
    if kb:
        p["reply_markup"] = kb
    if reply_to:
        p["reply_to_message_id"] = reply_to
    return _retry("sendMessage", **p)


def edit(chat_id, message_id, text, kb=None):
    p = {"chat_id": chat_id, "message_id": message_id, "text": text,
         "parse_mode": "HTML", "disable_web_page_preview": True}
    if kb:
        p["reply_markup"] = kb
    return _retry("editMessageText", **p)


def answer_cb(cb_id, text=None, alert=False):
    p = {"callback_query_id": cb_id}
    if text:
        p["text"] = text
        p["show_alert"] = alert
    return call("answerCallbackQuery", **p)


def delete(chat_id, message_id):
    return call("deleteMessage", chat_id=chat_id, message_id=message_id)


def get_updates(offset, timeout=25):
    res = call("getUpdates", http_timeout=timeout + 15, offset=offset, timeout=timeout,
               allowed_updates=["message", "callback_query"])
    return res.get("result", []) if res.get("ok") else []


def ikb(rows):
    """rows: list of list of (text, callback_data) or (text, url|'url:...')"""
    keyboard = []
    for row in rows:
        line = []
        for btn in row:
            text, data = btn[0], btn[1]
            if isinstance(data, dict):
                line.append({"text": text, **data})
            elif data.startswith("url:"):
                line.append({"text": text, "url": data[4:]})
            else:
                line.append({"text": text, "callback_data": data})
        keyboard.append(line)
    return {"inline_keyboard": keyboard}
