"""
DOOBAT - Configuration du webhook Telegram
Usage : python scripts/set_webhook.py [--delete] [--info]
Copyright 2026 Vincent Gallet - Vincesoft
"""

import asyncio
import configparser
import sys
import os

# Ajout du répertoire racine au path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from services.telegram_service import TelegramService


async def main():
    config = configparser.ConfigParser()
    if not config.read("config.ini"):
        print("ERREUR : config.ini introuvable.")
        sys.exit(1)

    telegram = TelegramService(config)

    # Parser les arguments
    args = sys.argv[1:]
    action = "set"
    if "--delete" in args:
        action = "delete"
    elif "--info" in args:
        action = "info"

    if action == "info":
        print("Récupération des informations du webhook...")
        info = await telegram.get_webhook_info()
        if info:
            print(f"  URL          : {info.get('url', 'Non configuré')}")
            print(f"  Pending      : {info.get('pending_update_count', 0)}")
            print(f"  Dernière err : {info.get('last_error_message', 'Aucune')}")
        else:
            print("Impossible de récupérer les informations du webhook.")
        return

    if action == "delete":
        print("Suppression du webhook...")
        success = await telegram.delete_webhook()
        if success:
            print("Webhook supprimé avec succès.")
        else:
            print("Erreur lors de la suppression du webhook.")
        return

    # Action par défaut : set
    base_url = config.get("SERVER", "base_url", fallback="")
    if not base_url:
        print("ERREUR : SERVER.base_url non configuré dans config.ini")
        sys.exit(1)

    webhook_url = f"{base_url.rstrip('/')}/webhook/telegram"
    secret = config.get("TELEGRAM", "webhook_secret", fallback="")

    print(f"Configuration du webhook Telegram...")
    print(f"  URL    : {webhook_url}")
    print(f"  Secret : {'configuré' if secret else 'ABSENT'}")

    success = await telegram.set_webhook(webhook_url, secret_token=secret)
    if success:
        print("\nWebhook configuré avec succès !")
        print("Vérification...")
        info = await telegram.get_webhook_info()
        if info:
            print(f"  URL active : {info.get('url', '?')}")
            print(f"  Pending    : {info.get('pending_update_count', 0)} update(s) en attente")
    else:
        print("ERREUR : Impossible de configurer le webhook.")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
