"""
Seed Email Templates Management Command

Seeds default email templates for all existing tenants.
Run this after deploying the new email template system to ensure
all existing tenants have their system email templates.
"""
from django.core.management.base import BaseCommand
from django_tenants.utils import schema_context, get_tenant_model

from smoothschedule.communication.messaging.models import PuckEmailTemplate
from smoothschedule.communication.messaging.email_types import EmailType
from smoothschedule.communication.messaging.default_templates import DEFAULT_TEMPLATES
from smoothschedule.communication.messaging.utils import add_component_ids


class Command(BaseCommand):
    help = 'Seed default email templates for all tenants'

    def add_arguments(self, parser):
        parser.add_argument(
            '--tenant',
            type=str,
            help='Only seed templates for this specific tenant schema',
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='Reset all templates to defaults (overwrites customizations)',
        )

    def handle(self, *args, **options):
        Tenant = get_tenant_model()

        if options['tenant']:
            # Single tenant mode
            try:
                tenant = Tenant.objects.get(schema_name=options['tenant'])
                tenants = [tenant]
            except Tenant.DoesNotExist:
                self.stderr.write(
                    self.style.ERROR(f"Tenant '{options['tenant']}' not found")
                )
                return
        else:
            # All tenants (excluding public schema)
            tenants = Tenant.objects.exclude(schema_name='public')

        self.stdout.write(f"Seeding email templates for {len(tenants)} tenant(s)...")

        total_created = 0
        total_updated = 0

        for tenant in tenants:
            created, updated = self._seed_for_tenant(
                tenant.schema_name,
                force=options['force']
            )
            total_created += created
            total_updated += updated

            if created > 0 or updated > 0:
                self.stdout.write(
                    f"  {tenant.schema_name}: created={created}, updated={updated}"
                )

        self.stdout.write(
            self.style.SUCCESS(
                f"\nDone! Created {total_created}, updated {total_updated} templates."
            )
        )

    def _seed_for_tenant(self, schema_name: str, force: bool = False) -> tuple:
        """Seed email templates for a single tenant."""
        created_count = 0
        updated_count = 0

        with schema_context(schema_name):
            for email_type in EmailType:
                default_data = DEFAULT_TEMPLATES.get(email_type.value)
                if not default_data:
                    continue

                existing = PuckEmailTemplate.objects.filter(
                    email_type=email_type.value
                ).first()

                # Add unique IDs to components (required by Puck)
                puck_data_with_ids = add_component_ids(default_data['puck_data'])

                if existing:
                    if force:
                        # Reset to default
                        existing.subject_template = default_data['subject_template']
                        existing.puck_data = puck_data_with_ids
                        existing.is_customized = False
                        existing.save()
                        updated_count += 1
                    # Skip if not forcing
                else:
                    # Create new template
                    PuckEmailTemplate.objects.create(
                        email_type=email_type.value,
                        subject_template=default_data['subject_template'],
                        puck_data=puck_data_with_ids,
                        is_active=True,
                        is_customized=False,
                    )
                    created_count += 1

        return created_count, updated_count
