import re
from pathlib import Path

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

from deals.models import WebsiteImage


IMAGE_PATTERN = re.compile(r'''(?:<img[^>]+src=["']|url\(["']?)([^"')]+)''', re.IGNORECASE)


class Command(BaseCommand):
    help = 'Add every static HTML image to the Website Images CMS library.'

    def handle(self, *args, **options):
        project_root = Path(settings.BASE_DIR).parent
        created = 0
        found = 0
        for page in sorted(project_root.glob('*.html')):
            html = page.read_text(encoding='utf-8', errors='ignore')
            for original_path in dict.fromkeys(IMAGE_PATTERN.findall(html)):
                if original_path.startswith(('data:', 'linear-gradient', '#')):
                    continue
                found += 1
                label = Path(original_path.split('?')[0]).stem.replace('-', ' ').replace('_', ' ').title()
                _, was_created = WebsiteImage.objects.get_or_create(
                    page_path=page.name,
                    original_path=original_path,
                    defaults={'label': label},
                )
                created += int(was_created)
        self.stdout.write(self.style.SUCCESS(f'Website image library ready: {found} references scanned, {created} added.'))
