"""
Your escape from migration hell.

Do not use this. You are being very careless if you do.

Force Run migration without InconsistentMigrationHistory nonsence.

This command will skip checking for consistent migration history and
it will als skip checking for conflicts.

It will just run the command for the app you specified. Sometimes that
is just what you need to get out of a bad situation.

This can also go wrong really fast though! You might mess up you migration
history even worse!
"""

from unittest import mock

from django.core.management.base import BaseCommand

try:
    from ocyan.i18n.db.migrations.loader import I18nMigrationLoader as MigrationLoader
    from ocyan.i18n.management.commands.i18nmigrate import Command as MigrateCommand

    migration_executor_module = "ocyan.i18n.db.migrations.executor.I18nMigrationLoader"
except ImportError:
    from django.core.management.commands.migrate import Command as MigrateCommand
    from django.db.migrations.loader import MigrationLoader

    migration_executor_module = "django.db.migrations.executor.MigrationLoader"


class NoWorriesnMigrationLoader(MigrationLoader):
    "Not a care in the world"

    def check_consistent_history(self, connection):
        pass

    def detect_conflicts(self):
        return []


class Command(BaseCommand):
    help = __doc__

    def add_arguments(self, parser):
        parser.add_argument(
            "app_label",
            help="App label of an application to synchronize the state, required for careless migrations",
        )
        parser.add_argument(
            "migration_name",
            nargs="?",
            help="Database state will be brought to the state after that migration.",
        )
        parser.add_argument(
            "--no-dry-run", action="store_true", help="Really commit to the database"
        )

    def handle(self, *args, **options):
        cmd = [
            "manage.py",
            "migrate",
            "--skip-checks",
            "--traceback",
            "--no-input",
            "--no-color",
            options["app_label"],
            options["migration_name"],
        ]
        if not options["no_dry_run"]:
            self.stdout.write(
                self.style.ERROR(
                    "\nAre you sure you want to seriously mess up your migrations table? Then check the help section for this command first.\n\n"
                )
            )
            self.print_help("manage.py", "careless_migrate")
            exit(1)

        with mock.patch(
            migration_executor_module,
            NoWorriesnMigrationLoader,
        ):
            migrate = MigrateCommand(
                stdout=self.stdout, stderr=self.stderr, no_color=True
            )
            migrate.run_from_argv(cmd)
