#!/usr/bin/env python3
"""Watch tunnel.log for the current trycloudflare URL; when it changes,
update the bot's menu button + send the user a fresh app button.

Run by sports-tunnel-watch.service (restarted by systemd with Restart=always).
"""
import json
import os
import re
import time
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.join(HERE, "tunnel.log")
STATE = os.path.join(HERE, "tunnel_url.txt")

TOKEN = ""
ENV_PATH = os.path.join(HERE, ".env")
if os.path.exists(ENV_PATH):
    for line in open(ENV_PATH):
        line = line.strip()
        if line.startswith("TELEGRAM_BOT_TOKEN="):
            TOKEN = line.split("=", 1)[1].strip()
if not TOKEN:
    raise SystemExit("no TELEGRAM_BOT_TOKEN in .env")


def api(method, payload):
    req = urllib.request.Request(
        f"https://api.telegram.org/bot{TOKEN}/{method}",
        data=json.dumps(payload).encode(),
        headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=25) as r:
        return json.loads(r.read().decode())


def current_url():
    try:
        txt = open(LOG, encoding="utf-8", errors="replace").read()
    except OSError:
        return None
    urls = re.findall(r"https://[a-z0-9-]+\.trycloudflare\.com", txt)
    return urls[-1] if urls else None


def main():
    last = None
    try:
        last = open(STATE).read().strip()
    except OSError:
        pass
    while True:
        url = current_url()
        if url and url != last:
            app = url + "/app/index.html"
            try:
                r = api("setChatMenuButton", {"menu_button": {
                    "type": "web_app", "text": "⚡ Predictions",
                    "web_app": {"url": app}}})
                if r.get("ok"):
                    api("sendMessage", {
                        "chat_id": 1067670558,
                        "text": "🔄 Mini-app moved to a new tunnel URL and the ⚡ Predictions button was updated automatically.",
                        "reply_markup": {"inline_keyboard": [[
                            {"text": "🏆 Open Predictions", "web_app": {"url": app}}]]}})
                    with open(STATE, "w") as f:
                        f.write(url)
                    last = url
            except Exception as e:
                print("update failed:", e, flush=True)
        time.sleep(20)


if __name__ == "__main__":
    main()