import csv
from django.core.management.base import BaseCommand
from core.models import CustomerTemplateMapping
from django.contrib.auth.models import User
import json

class Command(BaseCommand):
    help = "Import CustomerTemplateMapping records from a CSV file"

    def add_arguments(self, parser):
        parser.add_argument('csv_path', type=str, help='Path to the CSV file')
        parser.add_argument('--created_by', type=int, help='User ID to assign as created_by')

    def handle(self, *args, **options):
        csv_path = options['csv_path']
        created_by = None

        if options.get('created_by'):
            try:
                created_by = User.objects.get(id=options['created_by'])
            except User.DoesNotExist:
                self.stdout.write(self.style.ERROR(f"User with ID {options['created_by']} does not exist."))
                return

        with open(csv_path, newline='', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            count = 0

            for row in reader:
                name = row.get("customer_name")
                templates = row.get("template_names")

                if not name or not templates:
                    self.stderr.write(f"Skipping incomplete row: {row}")
                    continue

                try:
                    template_list = json.loads(templates)
                except json.JSONDecodeError:
                    self.stderr.write(f"Skipping row with invalid JSON: {templates}")
                    continue

                CustomerTemplateMapping.objects.update_or_create(
                    customer_name=name,
                    defaults={
                        "template_names": template_list,
                        "created_by": created_by,
                    }
                )

                count += 1

        self.stdout.write(self.style.SUCCESS(f"Imported {count} customer template mappings."))
