from django.contrib import admin
from .models import TelegramBot
from django.utils.html import format_html

@admin.register(TelegramBot)
class TelegramBotAdmin(admin.ModelAdmin):
    list_display = ("name", "username", "is_active", "get_assistant_name", "set_webhook_action")
    search_fields = ("name", "username")
    list_filter = ("is_active",)
    actions = ["set_webhooks"]

    @admin.action(description="Set webhooks for selected bots")
    def set_webhooks(self, request, queryset):
        base_url = request.build_absolute_uri("/")[:-1]  # Get base server URL
        results = []
        for bot in queryset:
            if bot.is_active:
                try:
                    result = bot.set_webhook(base_url)
                    self.message_user(
                        request,
                        f"Webhook set for {bot.name}: {result}",
                        level="success",
                    )
                except Exception as e:
                    self.message_user(
                        request,
                        f"Failed to set webhook for {bot.name}: {str(e)}",
                        level="error",
                    )
                results.append(result)
            else:
                self.message_user(
                    request,
                    f"Skipped inactive bot: {bot.name}",
                    level="warning",
                )

    def get_assistant_name(self, obj):
        """Show the name of the assistant linked to the bot."""
        return obj.assistant.name if obj.assistant else "None"

    get_assistant_name.short_description = "Assistant Name"

    def set_webhook_action(self, obj):
        """Button in the Django admin to manually trigger webhook setup."""
        return format_html(
            '<a class="button" href="{}">Set Webhook</a>',
            f"/admin/pxy_bots/set_webhook/{obj.id}/"
        )

    set_webhook_action.short_description = "Webhook"
