#!/usr/bin/env python3
from __future__ import annotations

import json
import os
import sys
import urllib.parse
import urllib.request
from pathlib import Path


def load_env_file(path: Path) -> None:
    if not path.exists():
        return
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        if not key:
            continue
        # сохраняем первое значение и игнорируем shell-комментарий после пробела
        value = value.split(" #", 1)[0].strip()
        if key not in os.environ:
            os.environ[key] = value


def api_call(token: str, method: str, payload: dict) -> dict:
    url = f"https://api.telegram.org/bot{token}/{method}"
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}, method="POST")
    with urllib.request.urlopen(req, timeout=20) as resp:
        return json.loads(resp.read().decode("utf-8"))


def main() -> int:
    root = Path(__file__).resolve().parents[1]
    load_env_file(root / ".env")

    token = os.getenv("BOT_TOKEN", "").strip()
    webapp_url = os.getenv("WEBAPP_URL", "").strip()
    if not token:
        print("BOT_TOKEN пустой в .env", file=sys.stderr)
        return 1
    if not webapp_url:
        print("WEBAPP_URL пустой в .env", file=sys.stderr)
        return 1

    parsed = urllib.parse.urlparse(webapp_url)
    if parsed.scheme != "https":
        print("WEBAPP_URL должен быть https", file=sys.stderr)
        return 1

    payload = {
        "menu_button": {
            "type": "web_app",
            "text": "Mini App",
            "web_app": {"url": webapp_url},
        }
    }
    result = api_call(token, "setChatMenuButton", payload)
    if not result.get("ok"):
        print(f"setChatMenuButton failed: {result}", file=sys.stderr)
        return 1

    print(f"Menu button updated: {webapp_url}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
