import re
from django.core.management.base import BaseCommand
from houslyspace.models import NetworkMonitoringOfferImages

# Stary i nowy prefix
OLD_PREFIX = "https://hously.space.s3.eu-north-1.amazonaws.com/images/"
NEW_PREFIX = "https://s3.eu-north-1.amazonaws.com/hously.space/images/"

class Command(BaseCommand):
    help = "Poprawia linki do zdjęć w polu images modelu NetworkMonitoringOfferImages"

    def handle(self, *args, **options):
        updated = 0
        for obj in NetworkMonitoringOfferImages.objects.iterator():
            if not obj.images:
                continue
            fixed = False
            new_images = []
            for url in obj.images:
                if url.startswith(OLD_PREFIX):
                    new_url = url.replace(OLD_PREFIX, NEW_PREFIX)
                    fixed = True
                else:
                    new_url = url
                new_images.append(new_url)
            if fixed:
                obj.images = new_images
                obj.save(update_fields=['images'])
                updated += 1
                self.stdout.write(f"Poprawiono rekord ID {updated}")
        self.stdout.write(self.style.SUCCESS(f"Poprawiono {updated} rekordów!"))
