from django.contrib import admin
from django.contrib import messages
from unfold.admin import ModelAdmin
from igny8_core.admin.base import SiteSectorAdminMixin, Igny8ModelAdmin
from .models import PublishingRecord, DeploymentRecord
from import_export.admin import ExportMixin
from import_export import resources


class PublishingRecordResource(resources.ModelResource):
    """Resource class for exporting Publishing Records"""
    class Meta:
        model = PublishingRecord
        fields = ('id', 'content__title', 'site__name', 'sector__name', 'destination', 
                  'status', 'destination_url', 'published_at', 'created_at')
        export_order = fields


@admin.register(PublishingRecord)
class PublishingRecordAdmin(ExportMixin, SiteSectorAdminMixin, Igny8ModelAdmin):
    resource_class = PublishingRecordResource
    list_display = [
        'content',
        'site',
        'sector',
        'destination',
        'status',
        'destination_url',
        'published_at',
    ]
    list_filter = ['destination', 'status', 'site']
    search_fields = ['content__title', 'destination', 'destination_url']
    readonly_fields = ['created_at', 'updated_at']
    actions = [
        'bulk_retry_failed',
        'bulk_cancel_pending',
        'bulk_mark_published',
    ]
    
    def bulk_retry_failed(self, request, queryset):
        """Retry failed publishing records"""
        failed_records = queryset.filter(status='failed')
        count = failed_records.update(status='pending')
        self.message_user(request, f'{count} failed record(s) marked for retry.', messages.SUCCESS)
    bulk_retry_failed.short_description = 'Retry failed publishes'
    
    def bulk_cancel_pending(self, request, queryset):
        """Cancel pending publishing records"""
        pending = queryset.filter(status__in=['pending', 'publishing'])
        count = pending.update(status='failed', error_message='Cancelled by admin')
        self.message_user(request, f'{count} publishing record(s) cancelled.', messages.SUCCESS)
    bulk_cancel_pending.short_description = 'Cancel pending publishes'
    
    def bulk_mark_published(self, request, queryset):
        """Mark selected records as published"""
        from django.utils import timezone
        count = queryset.update(status='published', published_at=timezone.now())
        self.message_user(request, f'{count} record(s) marked as published.', messages.SUCCESS)
    bulk_mark_published.short_description = 'Mark as published'


class DeploymentRecordResource(resources.ModelResource):
    """Resource class for exporting Deployment Records"""
    class Meta:
        model = DeploymentRecord
        fields = ('id', 'site__name', 'sector__name', 'version', 'deployed_version',
                  'status', 'deployment_url', 'deployed_at', 'created_at')
        export_order = fields


@admin.register(DeploymentRecord)
class DeploymentRecordAdmin(ExportMixin, SiteSectorAdminMixin, Igny8ModelAdmin):
    resource_class = DeploymentRecordResource
    list_display = [
        'site',
        'sector',
        'version',
        'deployed_version',
        'status',
        'deployment_url',
        'deployed_at',
    ]
    list_filter = ['status', 'site']
    search_fields = ['site__name', 'deployment_url']
    readonly_fields = ['created_at', 'updated_at']
    actions = [
        'bulk_retry_failed',
        'bulk_rollback',
        'bulk_cancel_pending',
    ]
    actions = [
        'bulk_retry_failed',
        'bulk_rollback',
        'bulk_cancel_pending',
    ]
    
    def bulk_retry_failed(self, request, queryset):
        """Retry failed deployments"""
        failed = queryset.filter(status='failed')
        count = failed.update(status='pending', error_message='')
        self.message_user(request, f'{count} failed deployment(s) marked for retry.', messages.SUCCESS)
    bulk_retry_failed.short_description = 'Retry failed deployments'
    
    def bulk_rollback(self, request, queryset):
        """Rollback selected deployments"""
        deployed = queryset.filter(status='deployed')
        count = deployed.update(status='rolled_back')
        self.message_user(request, f'{count} deployment(s) marked for rollback.', messages.SUCCESS)
    bulk_rollback.short_description = 'Rollback deployments'
    
    def bulk_cancel_pending(self, request, queryset):
        """Cancel pending deployments"""
        pending = queryset.filter(status__in=['pending', 'deploying'])
        count = pending.update(status='failed', error_message='Cancelled by admin')
        self.message_user(request, f'{count} deployment(s) cancelled.', messages.SUCCESS)
    bulk_cancel_pending.short_description = 'Cancel pending deployments'

