import json
import logging
from tqdm import tqdm

from django.core.management.base import BaseCommand
from django.db import IntegrityError

from apps.subscriptions.models import Extention

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    """Insert extension data from a JSON file"""

    help = 'Insert extension data from a JSON file'

    def add_arguments(self, parser):
        parser.add_argument('file_path', help='Path to the JSON file')

    def handle(self, *args, **options):
        """
        Handle the command to insert extension data from a JSON file

        Args:
            *args: List of positional arguments
            **options: Dictionary of keyword arguments
        """
        file_path = options['file_path']

        with open(file_path) as json_file:
            ext_data = json.load(json_file)

        with tqdm(total=len(ext_data), desc="Inserting extensions", unit="extension") as pbar:
            for ext in ext_data:
                try:
                    extension, created = Extention.objects.get_or_create(**ext)
                    if created:
                        self.stdout.write(self.style.SUCCESS(f'Successfully created extension {extension}'))
                    else:
                        self.stdout.write(self.style.SUCCESS(f'Extension {extension} already exists'))
                    pbar.update(1)
                except IntegrityError as e:
                    logger.error(f"Failed to create extension: {ext}. Error: {str(e)}")
                    self.stdout.write(self.style.ERROR(f'Failed to create extension {ext}'))
