"""
One-off diagnostic: for every Book with a cover set, check whether the
file actually exists on disk under MEDIA_ROOT. Read-only — makes no
changes. Used to scope a "covers not showing" report: is it every book,
or a specific subset?

Usage:
    python manage.py check_missing_covers
"""

import os

from django.conf import settings
from django.core.management.base import BaseCommand

from catalog_app.models import Book


class Command(BaseCommand):
    help = "Report every Book whose cover field points at a file that doesn't exist on disk."

    def handle(self, *args, **options):
        books = Book.objects.exclude(cover="").exclude(cover__isnull=True)
        total = books.count()
        missing = []
        for book in books:
            path = os.path.join(settings.MEDIA_ROOT, book.cover.name)
            if not os.path.exists(path):
                missing.append(book)

        self.stdout.write(f"Books with a cover set: {total}")
        self.stdout.write(f"Covers missing on disk: {len(missing)}\n")

        if missing:
            for book in missing:
                self.stdout.write(f"  id={book.pk:<6} {book.title[:60]:<60} -> {book.cover.name}")
        else:
            self.stdout.write(self.style.SUCCESS("All cover files are present on disk."))
