"""
Fetch artwork for external media items.

YouTube needs nothing: its thumbnail is derived from the URL on the fly.
SoundCloud needs one public oEmbed lookup per track, so the result is stored.

    python manage.py fetch_external_thumbs
    python manage.py fetch_external_thumbs --dry-run
    python manage.py fetch_external_thumbs --force   # refetch even if stored
"""
from django.core.management.base import BaseCommand

from apps.media.models import MediaItem


class Command(BaseCommand):
    help = 'Store SoundCloud artwork for external media items.'

    def add_arguments(self, parser):
        parser.add_argument('--dry-run', action='store_true')
        parser.add_argument('--force', action='store_true',
                            help='Refetch even when artwork is already stored.')

    def handle(self, *args, **options):
        qs = MediaItem.objects.filter(source_url__icontains='soundcloud.com')
        if not options['force']:
            qs = qs.filter(external_thumb='')

        items = list(qs)
        if not items:
            self.stdout.write('Nothing to do. Every SoundCloud item already has artwork.')
            return

        self.stdout.write(f'Checking {len(items)} SoundCloud item(s).')
        found = missed = 0

        for item in items:
            if options['dry_run']:
                self.stdout.write(f'  #{item.pk} {item.title}: would look up artwork.')
                found += 1
                continue

            url = item.fetch_external_thumb()
            if url:
                found += 1
                self.stdout.write(f'  #{item.pk} {item.title}: {url}')
            else:
                missed += 1
                self.stdout.write(self.style.WARNING(
                    f'  #{item.pk} {item.title}: no artwork returned.'
                ))

        verb = 'would fetch' if options['dry_run'] else 'fetched'
        self.stdout.write(self.style.SUCCESS(f'Done. {verb} {found}, missed {missed}.'))
