from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from workouts.importer import import_flexify

User = get_user_model()


class Command(BaseCommand):
    help = "Import workouts and routines from a Flexify backup"

    def add_arguments(self, parser):
        parser.add_argument(
            "--sqlite",
            dest="sqlite",
            default=None,
            help="Path to a Flexify sqlite backup file",
        )
        parser.add_argument(
            "--csv",
            dest="csv",
            default=None,
            help="Path to a Flexify plans CSV file",
        )
        parser.add_argument(
            "--user",
            dest="user",
            required=True,
            help="Email of the user to attach the scrobbles to",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="Report what would be imported without writing anything",
        )
        parser.add_argument(
            "--source",
            dest="source",
            default="Flexify Import",
            help="Scrobble source label (default: Flexify Import)",
        )

    def handle(self, *args, **options):
        user = User.objects.filter(email=options["user"]).first()
        if not user:
            raise CommandError(f"No user found with email {options['user']}")

        if not options.get("sqlite") and not options.get("csv"):
            raise CommandError("Provide --sqlite and/or --csv")

        result = import_flexify(
            sqlite_path=options.get("sqlite"),
            csv_path=options.get("csv"),
            user_id=user.id,
            dry_run=options.get("dry_run"),
            source=options.get("source"),
        )
        self.stdout.write(
            self.style.SUCCESS(
                f"Import finished: {result['routines_created']} routines created, "
                f"{result['routines_updated']} routines updated, "
                f"{result['exercises_created']} exercises created, "
                f"{result['scrobbles_created']} scrobbles created, "
                f"{result['scrobbles_existing']} scrobbles already present, "
                f"{result['scrobbles_skipped']} skipped"
            )
        )
