"""
One-off diagnostic: for every FileField/ImageField on every model in the
project, check whether the file it points at actually exists on disk under
MEDIA_ROOT. Read-only — makes no changes.

Broader than check_missing_covers (which only looked at Book.cover) — this
walks every model so it catches author images, homepage images, expense
receipts, M-Pesa paybill proofs, application/legacy-invitation covers, etc.

Usage:
    python manage.py check_missing_media
"""

import os

from django.apps import apps
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db.models import FileField


class Command(BaseCommand):
    help = "Report every FileField/ImageField value across all models that points at a file missing on disk."

    def handle(self, *args, **options):
        total_checked = 0
        total_missing = 0

        for model in apps.get_models():
            file_fields = [f for f in model._meta.get_fields() if isinstance(f, FileField)]
            if not file_fields:
                continue

            missing_for_model = []
            for obj in model.objects.all():
                for field in file_fields:
                    value = getattr(obj, field.name)
                    if not value:
                        continue
                    total_checked += 1
                    path = os.path.join(settings.MEDIA_ROOT, value.name)
                    if not os.path.exists(path):
                        total_missing += 1
                        missing_for_model.append((obj.pk, field.name, value.name))

            if missing_for_model:
                label = f"{model._meta.app_label}.{model.__name__}"
                self.stdout.write(self.style.ERROR(f"\n{label} — {len(missing_for_model)} missing:"))
                for pk, field_name, path in missing_for_model:
                    self.stdout.write(f"  id={pk:<6} {field_name:<20} -> {path}")

        self.stdout.write(f"\nTotal file fields checked: {total_checked}")
        if total_missing:
            self.stdout.write(self.style.ERROR(f"Total missing on disk: {total_missing}"))
        else:
            self.stdout.write(self.style.SUCCESS("Nothing missing — every referenced file exists on disk."))
