import hmac
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
from pathlib import Path
import re
import signal
import sys
import time
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import build_opener, HTTPRedirectHandler, Request


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *_args, **_kwargs):
        return None


class UpdateTooLarge(ValueError):
    pass


def webhook_body(handler):
    """A reverse proxy may forward the JSON with a length or in HTTP/1.1 chunks."""
    limit = 65536
    stream = handler.rfile
    transfer = handler.headers.get_all("Transfer-Encoding")
    if not transfer:
        size = int(handler.headers.get("Content-Length", "0"))
        if not 0 < size <= limit:
            raise UpdateTooLarge()
        return stream.read(size)
    if [value.lower().strip() for value in transfer] != ["chunked"] or "Content-Length" in handler.headers:
        raise ValueError("Unsupported transfer encoding")
    body = bytearray()
    while True:
        line = stream.readline(1025)
        if len(line) > 1024 or not line.endswith(b"\r\n"):
            raise ValueError("Invalid chunk header")
        digits = line[:-2].split(b";", 1)[0]
        if not re.fullmatch(rb"[0-9a-fA-F]{1,16}", digits):
            raise ValueError("Invalid chunk size")
        size = int(digits, 16)
        if not size:
            # The starter closes each response, so trailing headers are unused.
            handler.close_connection = True
            return body
        if size > limit - len(body):
            raise UpdateTooLarge()
        body.extend(stream.read(size))
        if stream.read(2) != b"\r\n":
            raise ValueError("Incomplete chunk")


def start():
    token = os.environ.get("TELEGRAM_BOT_TOKEN", "")
    webhook = os.environ.get("TELEGRAM_WEBHOOK_URL", "")
    delivery = os.environ.get("BH_TELEGRAM_MODE") or ("webhook" if webhook else "polling")
    secret = os.environ.get("TELEGRAM_WEBHOOK_SECRET", "")
    if not re.fullmatch(r"[0-9]+:[a-zA-Z0-9_-]+", token):
        raise RuntimeError("Add TELEGRAM_BOT_TOKEN in Variables.")
    opener = build_opener(NoRedirect)

    def api(method, **fields):
        request = Request(
            "https://api.telegram.org/bot" + token + "/" + method,
            data=json.dumps(fields).encode(),
            headers={"Content-Type": "application/json"},
        )
        try:
            with opener.open(request, timeout=38) as response:
                result = json.load(response)
                if result.get("ok"):
                    return result["result"]
        except HTTPError as error:
            raise RuntimeError("Telegram returned HTTP " + str(error.code)) from None
        except OSError:
            raise RuntimeError("Could not connect to Telegram.") from None
        raise RuntimeError("Telegram rejected the request.")

    bot = api("getMe")
    folder = Path(".telegram-state")
    folder.mkdir(mode=0o700, exist_ok=True)
    state = folder / "updates.json"
    recent = []
    registered_webhook = ""
    if state.exists():
        snapshot = json.loads(state.read_text())
        if snapshot.get("botId") == bot["id"]:
            recent = snapshot["ids"][-512:]
            registered_webhook = snapshot.get("webhook", "")

    def persist():
        pending = state.with_suffix(".tmp")
        pending.write_text(json.dumps({"botId": bot["id"], "ids": recent, "webhook": registered_webhook}))
        pending.replace(state)

    def answer(update):
        update_id = update["update_id"]
        if update_id in recent:
            return
        message = update.get("message", {})
        chat = message.get("chat", {})
        if chat.get("type") == "private" and message.get("text") == "/start":
            api("sendMessage", chat_id=chat["id"], text="Your bot is running.")
        recent.append(update_id)
        del recent[:-512]
        persist()

    if delivery == "polling":
        current = api("getWebhookInfo").get("url")
        if current:
            if current != registered_webhook:
                raise RuntimeError("Remove the existing webhook before using polling.")
            api("deleteWebhook", drop_pending_updates=False)
            registered_webhook = ""
            persist()
        print("Telegram polling ready.", flush=True)
        offset = 0
        while True:
            try:
                for update in api("getUpdates", offset=offset, timeout=25, allowed_updates=["message"]):
                    answer(update)
                    offset = update["update_id"] + 1
            except (RuntimeError, OSError):
                print("Telegram polling paused. Retrying shortly.", flush=True)
                time.sleep(3)

    if delivery != "webhook":
        raise RuntimeError("Unknown Telegram delivery mode.")
    url = urlsplit(webhook)
    port = int(os.environ.get("SERVER_PORT", "0"))
    if (
        url.scheme != "https" or not url.hostname or url.username or url.password
        or url.path != "/telegram" or url.query or url.fragment
        or not re.fullmatch(r"[a-zA-Z0-9_-]{16,256}", secret)
        or not 1024 <= port <= 65535
    ):
        raise RuntimeError("Set the HTTPS webhook URL, webhook secret and assigned port.")

    class Handler(BaseHTTPRequestHandler):
        def setup(self):
            self.request.settimeout(8)
            super().setup()

        def log_message(self, *_args):
            pass

        def status(self, code):
            self.send_response(code)
            self.send_header("Content-Length", "0")
            self.end_headers()

        def do_GET(self):
            self.status(200 if self.path == "/healthz" else 404)

        def do_POST(self):
            if self.path != "/telegram":
                self.status(404)
                return
            supplied = self.headers.get("X-Telegram-Bot-Api-Secret-Token", "").encode()
            if not hmac.compare_digest(supplied, secret.encode()):
                self.status(403)
                return
            try:
                update = json.loads(webhook_body(self))
                if not isinstance(update, dict) or type(update.get("update_id")) is not int:
                    self.status(400)
                    return
            except UpdateTooLarge:
                self.status(413)
                return
            except (ValueError, OSError):
                self.status(400)
                return
            try:
                answer(update)
                self.status(204)
            except (RuntimeError, OSError):
                self.status(503)

    with HTTPServer(("0.0.0.0", port), Handler) as server:
        api("setWebhook", url=webhook, secret_token=secret, max_connections=1, allowed_updates=["message"])
        registered_webhook = webhook
        persist()
        print("Telegram webhook ready.", flush=True)
        server.serve_forever()


if __name__ == "__main__":
    for signum in (signal.SIGINT, signal.SIGTERM):
        signal.signal(signum, lambda *_: sys.exit(0))
    try:
        start()
    except (RuntimeError, ValueError, OSError):
        print("Telegram startup failed. Check your token, delivery mode and Variables.", flush=True)
        raise SystemExit(1) from None
