import os
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Simulate a local image upload without using an endpoint'

    def add_arguments(self, parser):
        parser.add_argument('--file', type=str, required=True, help='Path to the image file to simulate upload')

    def handle(self, *args, **kwargs):
        file_path = kwargs['file']

        # Check if the file exists
        if not os.path.isfile(file_path):
            self.stdout.write(self.style.ERROR(f"File not found: {file_path}"))
            return

        # Simulate a file upload using Django's SimpleUploadedFile
        try:
            with open(file_path, 'rb') as f:
                file_name = os.path.basename(file_path)
                uploaded_file = SimpleUploadedFile(file_name, f.read(), content_type='image/jpeg')

                # Simulate handling the uploaded file
                self.stdout.write(f"File Name: {uploaded_file.name}")
                self.stdout.write(f"File Size: {uploaded_file.size}")
                self.stdout.write(f"File Content Type: {uploaded_file.content_type}")

                # Here you could add any additional logic to process the file locally
                # For example, saving it to the file system or processing its content

                # Example: Save file to media directory (if needed)
                from django.conf import settings
                save_path = os.path.join(settings.MEDIA_ROOT, 'uploads', uploaded_file.name)
                os.makedirs(os.path.dirname(save_path), exist_ok=True)
                with open(save_path, 'wb') as output_file:
                    output_file.write(uploaded_file.read())
                self.stdout.write(self.style.SUCCESS(f"File saved to {save_path}"))

        except Exception as e:
            self.stdout.write(self.style.ERROR(f"An error occurred during file handling: {e}"))
