import os

from django.core.management.base import BaseCommand
from django.db import transaction

from apps.parks.models import ParkPhoto
from apps.rides.models import RidePhoto


class Command(BaseCommand):
    help = "Fix photo paths in database to match actual file locations"

    def handle(self, *args, **kwargs):
        self.stdout.write("Fixing photo paths in database...")

        # Get all photos
        park_photos = ParkPhoto.objects.all()
        ride_photos = RidePhoto.objects.all()

        # Process park photos
        for photo in park_photos:
            try:
                with transaction.atomic():
                    # Get current file path
                    current_name = photo.image.name

                    # Remove any 'media/' prefix if it exists
                    if current_name.startswith("media/"):
                        # Remove 'media/' prefix
                        current_name = current_name[6:]

                    parts = current_name.split("/")

                    if len(parts) >= 2:
                        content_type = "park"
                        identifier = photo.park.slug

                        # Look for files in the media directory
                        media_dir = os.path.join("media", content_type, identifier)
                        if os.path.exists(media_dir):
                            files = [
                                f
                                for f in os.listdir(media_dir)
                                if not f.startswith(".")  # Skip hidden files
                                and not f.startswith("tmp")  # Skip temp files
                                and os.path.isfile(os.path.join(media_dir, f))
                            ]

                            if files:
                                # Get the first file and update the database
                                # record
                                file_path = os.path.join(content_type, identifier, files[0])
                                if os.path.exists(os.path.join("media", file_path)):
                                    photo.image.name = file_path
                                    photo.save()
                                    self.stdout.write(
                                        f"Updated path for park photo {
                                            photo.id} to {file_path}"
                                    )
                                else:
                                    self.stdout.write(
                                        f"File not found for park photo {
                                            photo.id}: {file_path}"
                                    )
                            else:
                                self.stdout.write(
                                    f"No files found in directory for park photo {
                                        photo.id}: {media_dir}"
                                )
                        else:
                            self.stdout.write(
                                f"Directory not found for park photo {
                                    photo.id}: {media_dir}"
                            )

            except Exception as e:
                self.stdout.write(f"Error updating park photo {photo.id}: {str(e)}")
                continue

        # Process ride photos
        for photo in ride_photos:
            try:
                with transaction.atomic():
                    # Get current file path
                    current_name = photo.image.name

                    # Remove any 'media/' prefix if it exists
                    if current_name.startswith("media/"):
                        # Remove 'media/' prefix
                        current_name = current_name[6:]

                    parts = current_name.split("/")

                    if len(parts) >= 2:
                        content_type = "ride"
                        identifier = photo.ride.slug

                        # Look for files in the media directory
                        media_dir = os.path.join("media", content_type, identifier)
                        if os.path.exists(media_dir):
                            files = [
                                f
                                for f in os.listdir(media_dir)
                                if not f.startswith(".")  # Skip hidden files
                                and not f.startswith("tmp")  # Skip temp files
                                and os.path.isfile(os.path.join(media_dir, f))
                            ]

                            if files:
                                # Get the first file and update the database
                                # record
                                file_path = os.path.join(content_type, identifier, files[0])
                                if os.path.exists(os.path.join("media", file_path)):
                                    photo.image.name = file_path
                                    photo.save()
                                    self.stdout.write(
                                        f"Updated path for ride photo {
                                            photo.id} to {file_path}"
                                    )
                                else:
                                    self.stdout.write(
                                        f"File not found for ride photo {
                                            photo.id}: {file_path}"
                                    )
                            else:
                                self.stdout.write(
                                    f"No files found in directory for ride photo {
                                        photo.id}: {media_dir}"
                                )
                        else:
                            self.stdout.write(
                                f"Directory not found for ride photo {
                                    photo.id}: {media_dir}"
                            )

            except Exception as e:
                self.stdout.write(f"Error updating ride photo {photo.id}: {str(e)}")
                continue

        self.stdout.write("Finished fixing photo paths")
