"""
Management command to create default home pages for all existing sites.
"""
from django.core.management.base import BaseCommand
from smoothschedule.platform.tenant_sites.models import Site, Page


class Command(BaseCommand):
    help = 'Create default home pages for all existing sites that do not have one, or populate empty ones'

    def handle(self, *args, **options):
        sites = Site.objects.all()
        created_count = 0
        populated_count = 0
        skipped_count = 0

        for site in sites:
            home_page = site.pages.filter(is_home=True).first()

            if not home_page:
                # No home page exists - create one
                self.stdout.write(f'Creating default page for {site.tenant.name}...')
                site.create_default_page()
                created_count += 1
            elif not home_page.puck_data.get('content') or len(home_page.puck_data.get('content', [])) == 0:
                # Home page exists but is empty - populate it
                self.stdout.write(f'Populating empty page for {site.tenant.name}...')
                default_content = {
                    'content': [
                        {
                            'type': 'Hero',
                            'props': {
                                'id': 'Hero-default',
                                'title': f'Welcome to {site.tenant.name}',
                                'subtitle': 'Book your appointment online',
                                'align': 'center',
                                'backgroundColor': '#f3f4f6',
                                'textColor': '#111827'
                            }
                        },
                        {
                            'type': 'Booking',
                            'props': {
                                'id': 'Booking-default',
                                'headline': 'Schedule Your Appointment',
                                'subheading': 'Choose a service and time that works for you',
                                'accentColor': '#4f46e5',
                                'buttonLabel': 'Book Now'
                            }
                        }
                    ],
                    'root': {}
                }
                home_page.puck_data = default_content
                home_page.save()
                populated_count += 1
            else:
                skipped_count += 1

        self.stdout.write(
            self.style.SUCCESS(
                f'Successfully created {created_count} new pages and populated {populated_count} empty pages. '
                f'Skipped {skipped_count} sites with existing content.'
            )
        )
