import os
import logging
from django.core.management.base import BaseCommand
from advertisements.models import Advertisement
from cloud_storage.services import upload_advertisement_image_to_ovh

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = "Migruje obrazki z lokalnych /media/ do OVH S3 i aktualizuje linki w bazie"

    def handle(self, *args, **options):
        ads = Advertisement.objects.all()
        media_root = os.path.join(os.getcwd(), "media")

        updated = 0
        skipped = 0
        not_found = 0

        for ad in ads:
            new_images = []
            changed = False

            for idx, image_path in enumerate(ad.images):
                try:
                    # Skip jeśli już jest link OVH
                    if image_path.startswith("http"):
                        new_images.append(image_path)
                        skipped += 1
                        continue

                    # Naprawiamy ścieżkę z podwójnym "/media/"
                    cleaned_path = image_path.replace("/media/", "", 1).lstrip("/")
                    full_path = os.path.join(media_root, cleaned_path)

                    if not os.path.exists(full_path):
                        self.stdout.write(f"\u26a0\ufe0f  Nie znaleziono pliku: {full_path}")
                        not_found += 1
                        continue

                    with open(full_path, "rb") as f:
                        file_data = f.read()
                        url = upload_advertisement_image_to_ovh(file_data, ad.id, idx)

                        if url:
                            new_images.append(url)
                            changed = True
                        else:
                            self.stdout.write(f"\u274c  B\u0142\u0105d uploadu: {full_path}")

                except Exception as e:
                    self.stdout.write(f"\u274c  Wyj\u0105tek dla {image_path}: {str(e)}")

            if changed:
                ad.images = new_images
                ad.save()
                updated += 1

        self.stdout.write("\n\ud83d\udcca Podsumowanie:")
        self.stdout.write(f"\u2705 Zmienione: {updated}")
        self.stdout.write(f"\u23ed\ufe0f  Pomini\u0119te (ju\u017c linki): {skipped}")
        self.stdout.write(f"\u274c Nieudane: {not_found}")