#!/usr/bin/env python3
# =============================================================
# setup_webhook.py — Reģistrē Webhook Telegram
# Palaid: cPanel → Python App → Execute python script
# =============================================================

import os
import requests
from pathlib import Path

# Ielādē .env manuāli
env_path = Path(__file__).resolve().parent / ".env"
if env_path.exists():
    with open(env_path) as f:
        for line in f:
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, _, val = line.partition("=")
                os.environ.setdefault(key.strip(), val.strip())

TOKEN  = os.getenv("TELEGRAM_BOT_TOKEN", "")
SECRET = os.getenv("TELEGRAM_WEBHOOK_SECRET", "")
API_URL = os.getenv("API_BASE_URL", "https://api.agent.melgalis.lv")

print(f"TOKEN:  {TOKEN[:20]}...")
print(f"SECRET: {SECRET}")
print(f"API_URL: {API_URL}")

WEBHOOK_URL = f"{API_URL}/webhook/telegram/{SECRET}/"
print(f"\nWebhook URL: {WEBHOOK_URL}")

# Reģistrē
resp = requests.post(
    f"https://api.telegram.org/bot{TOKEN}/setWebhook",
    json={"url": WEBHOOK_URL, "allowed_updates": ["message", "callback_query"]}
)
data = resp.json()

if data.get("ok"):
    print(f"\n✅ Webhook reģistrēts veiksmīgi!")
    print(f"   URL: {WEBHOOK_URL}")
else:
    print(f"\n❌ Kļūda: {data}")

# Pārbauda pašreizējo webhook
info = requests.get(f"https://api.telegram.org/bot{TOKEN}/getWebhookInfo").json()
print(f"\nAktīvais webhook: {info.get('result', {}).get('url', 'nav')}")
