from django.core.management.base import BaseCommand

from vbv_lernwelt.files.integrations import s3_get_client, s3_get_credentials
from vbv_lernwelt.files.models import UploadFile


class Command(BaseCommand):
    help = "Delete unused files from S3"

    def add_arguments(self, parser):
        parser.add_argument(
            "--dry-run",
            action="store_true",
            dest="dry_run",
            default=False,
            help="Dry run",
        )

    def handle(self, *args, **options):
        dry_run = options["dry_run"]
        credentials = s3_get_credentials()
        s3_client = s3_get_client()
        num_deleted = 0

        if dry_run:
            print("------ DRY RUN -------")

        result = s3_client.list_objects_v2(
            Bucket=credentials.bucket_name, Prefix="circledocuments/"
        )
        for contents in result.get("Contents"):
            try:
                UploadFile.objects.get(file=contents["Key"])
            except UploadFile.DoesNotExist:
                print(f"Deleting {contents['Key']}")
                if not dry_run:
                    s3_client.delete_object(
                        Bucket=credentials.bucket_name, Key=contents["Key"]
                    )
                num_deleted += 1

        print(f"Deleted {num_deleted} files in bucket {credentials.bucket_name}")
