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

class Command(BaseCommand):
    help = 'Change for True or False the DEBUG variable in settings.py'

    def handle(self, *args, **options):
        try:
            # Open the settings.py file
            project_name = os.path.basename(settings.BASE_DIR)
            settings_file = os.path.join(settings.BASE_DIR, project_name, 'settings.py')
            with open(settings_file, 'r') as f:
                contents = f.read()

            # Replace the value of DEBUG
            if 'DEBUG = True' in contents:
                contents = contents.replace('DEBUG = True', 'DEBUG = False')
                new_value = False
            else:
                contents = contents.replace('DEBUG = False', 'DEBUG = True')
                new_value = True

            # Write the modified contents back to the file
            with open(settings_file, 'w') as f:
                f.write(contents)

            self.stdout.write(self.style.SUCCESS(f"DEBUG set to {new_value}"))
        except Exception as e:
            self.stdout.write(self.style.ERROR('Error while ' + str(e)))

