from django.contrib import admin
from django.contrib import messages
from unfold.admin import ModelAdmin
from igny8_core.admin.base import AccountAdminMixin, Igny8ModelAdmin
from .models import OptimizationTask
from import_export.admin import ExportMixin
from import_export import resources


class OptimizationTaskResource(resources.ModelResource):
    """Resource class for exporting Optimization Tasks"""
    class Meta:
        model = OptimizationTask
        fields = ('id', 'content__title', 'account__name', 'status', 
                  'credits_used', 'created_at')
        export_order = fields


@admin.register(OptimizationTask)
class OptimizationTaskAdmin(ExportMixin, AccountAdminMixin, Igny8ModelAdmin):
    resource_class = OptimizationTaskResource
    list_display = ['content', 'account', 'status', 'credits_used', 'created_at']
    list_filter = ['status', 'created_at']
    search_fields = ['content__title', 'account__name']
    readonly_fields = ['created_at', 'updated_at']
    actions = [
        'bulk_mark_completed',
        'bulk_mark_failed',
        'bulk_retry',
    ]
    
    def bulk_mark_completed(self, request, queryset):
        updated = queryset.update(status='completed')
        self.message_user(request, f'{updated} optimization task(s) marked as completed.', messages.SUCCESS)
    bulk_mark_completed.short_description = 'Mark as completed'
    
    def bulk_mark_failed(self, request, queryset):
        updated = queryset.update(status='failed')
        self.message_user(request, f'{updated} optimization task(s) marked as failed.', messages.SUCCESS)
    bulk_mark_failed.short_description = 'Mark as failed'
    
    def bulk_retry(self, request, queryset):
        updated = queryset.filter(status='failed').update(status='pending')
        self.message_user(request, f'{updated} failed optimization task(s) queued for retry.', messages.SUCCESS)
    bulk_retry.short_description = 'Retry failed tasks'
