from django.apps import AppConfig


class LinksConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'links'

    def ready(self):
        # Import signals to register them
        import links.signals
        self._register_job_types()

    def _register_job_types(self):
        from . import job_registry
        if job_registry.all_types():
            return  # already registered (e.g. double-init in test runner)

        from .models import Screenshot, Page, FileUpload
        from django.urls import reverse

        # ── Screenshots ──────────────────────────────────────────────────
        def ss_stats():
            return {
                'total': Screenshot.objects.count(),
                'pending': Screenshot.objects.filter(status=Screenshot.Status.PENDING).count(),
                'processing': Screenshot.objects.filter(status=Screenshot.Status.PROCESSING).count(),
                'completed': Screenshot.objects.filter(status=Screenshot.Status.COMPLETED).count(),
                'failed': Screenshot.objects.filter(status=Screenshot.Status.FAILED).count(),
            }

        def ss_queryset(sf):
            qs = Screenshot.objects.select_related('page').order_by('-updated_at')
            return qs if sf == 'all' else qs.filter(status=sf)

        def ss_serialize(obj):
            return {
                'id': str(obj.id),
                'title': (obj.page.title or obj.page.url) if obj.page else '?',
                'detail_url': reverse('page-detail', args=[obj.page.pk]) if obj.page else '#',
                'status': obj.status,
                'retry': obj.retry_count,
                'retry_max': 3,
                'error': obj.error or '',
                'updated_at': obj.updated_at,
                'extra': {},
            }

        job_registry.register({
            'id': 'screenshots',
            'label': 'Screenshots',
            'icon_color': 'text-indigo-500',
            'icon_path': (
                'M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86'
                'a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2'
                ' 2H5a2 2 0 01-2-2V9z M15 13a3 3 0 11-6 0 3 3 0 016 0z'
            ),
            'title_label': 'Page',
            'status_choices': [
                ('all', 'All'), ('pending', 'Pending'), ('processing', 'Processing'),
                ('completed', 'Completed'), ('failed', 'Failed'),
            ],
            'columns': ['id', 'title', 'status', 'retry', 'error', 'updated'],
            'get_stats': ss_stats,
            'get_queryset': ss_queryset,
            'serialize': ss_serialize,
            'bulk_actions': {
                'retry': 'bulk_retry_screenshots',
                'fail': 'bulk_fail_screenshots',
                'delete': 'bulk_delete_screenshots',
            },
        })

        # ── Page Processing ─────────────────────────────────────────────
        def pg_stats():
            return {
                'total': Page.objects.count(),
                'pending': Page.objects.filter(process_status=Page.ProcessStatus.PENDING).count(),
                'processing': Page.objects.filter(process_status=Page.ProcessStatus.PROCESSING).count(),
                'completed': Page.objects.filter(process_status=Page.ProcessStatus.COMPLETED).count(),
                'failed': Page.objects.filter(process_status=Page.ProcessStatus.FAILED).count(),
            }

        def pg_queryset(sf):
            qs = Page.objects.order_by('-updated_at')
            return qs if sf == 'all' else qs.filter(process_status=sf)

        def pg_serialize(obj):
            return {
                'id': str(obj.id),
                'title': obj.title or obj.url,
                'detail_url': reverse('page-detail', args=[obj.pk]),
                'status': obj.process_status,
                'retry': obj.retry_count,
                'retry_max': 3,
                'error': obj.error_message or '',
                'updated_at': obj.updated_at,
                'extra': {},
            }

        job_registry.register({
            'id': 'pages',
            'label': 'Page Processing',
            'icon_color': 'text-purple-500',
            'icon_path': (
                'M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2'
                'V7m2 13a2 2 0 002-2V9.5a2 2 0 00-2-2h-2'
            ),
            'title_label': 'Title / URL',
            'status_choices': [
                ('all', 'All'), ('pending', 'Pending'), ('processing', 'Processing'),
                ('completed', 'Completed'), ('failed', 'Failed'),
            ],
            'columns': ['id', 'title', 'status', 'retry', 'error', 'updated'],
            'get_stats': pg_stats,
            'get_queryset': pg_queryset,
            'serialize': pg_serialize,
            'bulk_actions': {
                'retry': 'bulk_retry_pages',
                'fail': 'bulk_fail_pages',
                'delete': 'bulk_delete_pages',
            },
        })

        # ── Image Imports ──────────────────────────────────────────────
        def ii_stats():
            base = FileUpload.objects.filter(source_url__isnull=False).exclude(source_url='')
            return {
                'total': base.count(),
                'pending': base.filter(size=0).count(),
                'completed': base.filter(size__gt=0).count(),
            }

        def ii_queryset(sf):
            base = FileUpload.objects.filter(
                source_url__isnull=False,
            ).exclude(source_url='').order_by('-updated_at')
            if sf == 'pending':
                return base.filter(size=0)
            if sf == 'completed':
                return base.filter(size__gt=0)
            return base

        def ii_serialize(obj):
            return {
                'id': str(obj.id),
                'title': obj.name,
                'detail_url': getattr(obj, 'download_url', '#') or '#',
                'status': 'completed' if obj.size > 0 else 'pending',
                'retry': None,
                'retry_max': None,
                'error': '',
                'updated_at': obj.updated_at,
                'extra': {
                    'source_url': obj.source_url or '',
                    'formatted_size': (
                        getattr(obj, 'formatted_size', '') if obj.size > 0 else ''
                    ),
                },
            }

        job_registry.register({
            'id': 'image_imports',
            'label': 'Image Imports',
            'icon_color': 'text-green-500',
            'icon_path': (
                'M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828'
                ' 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12'
                'a2 2 0 002 2z'
            ),
            'title_label': 'Filename',
            'status_choices': [
                ('all', 'All'), ('pending', 'Pending'), ('completed', 'Done'),
            ],
            'columns': ['id', 'title', 'source_url', 'status', 'size', 'updated'],
            'get_stats': ii_stats,
            'get_queryset': ii_queryset,
            'serialize': ii_serialize,
            'bulk_actions': {
                'retry': 'bulk_retry_image_imports',
                'delete': 'bulk_delete_image_imports',
            },
        })

