"""
Management command to create demo appointments for the current month.
"""
import random
from datetime import datetime, timedelta
from decimal import Decimal

from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from django.utils import timezone

from smoothschedule.scheduling.schedule.models import Event, Resource, Service, Participant
from smoothschedule.identity.users.models import User


class Command(BaseCommand):
    help = 'Create demo appointments spanning the current month'

    def add_arguments(self, parser):
        parser.add_argument(
            '--clear',
            action='store_true',
            help='Clear existing events before creating new ones',
        )
        parser.add_argument(
            '--count',
            type=int,
            default=50,
            help='Number of appointments to create (default: 50)',
        )

    def handle(self, *args, **options):
        if options['clear']:
            deleted_count = Event.objects.all().delete()[0]
            self.stdout.write(f'Deleted {deleted_count} existing events')

        # Ensure we have some resources
        resources = list(Resource.objects.filter(is_active=True))
        if not resources:
            self.stdout.write('Creating demo resources...')
            resources = [
                Resource.objects.create(name='Sarah Johnson', type='STAFF', description='Senior Stylist'),
                Resource.objects.create(name='Mike Chen', type='STAFF', description='Barber'),
                Resource.objects.create(name='Room A', type='ROOM', description='Main treatment room'),
                Resource.objects.create(name='Room B', type='ROOM', description='Private consultation'),
            ]
            self.stdout.write(f'Created {len(resources)} resources')

        # Ensure we have some services
        services = list(Service.objects.filter(is_active=True))
        if not services:
            self.stdout.write('Creating demo services...')
            services = [
                Service.objects.create(name='Haircut', duration=30, price=Decimal('35.00')),
                Service.objects.create(name='Hair Coloring', duration=90, price=Decimal('120.00')),
                Service.objects.create(name='Beard Trim', duration=15, price=Decimal('15.00')),
                Service.objects.create(name='Full Styling', duration=60, price=Decimal('75.00')),
                Service.objects.create(name='Consultation', duration=30, price=Decimal('0.00')),
            ]
            self.stdout.write(f'Created {len(services)} services')

        # Ensure we have customer users
        customers = list(User.objects.filter(role=User.Role.CUSTOMER))
        if not customers:
            self.stdout.write('Creating demo customers...')
            customer_data = [
                ('alice', 'Alice Williams', 'alice@example.com'),
                ('bob', 'Bob Martinez', 'bob@example.com'),
                ('carol', 'Carol Davis', 'carol@example.com'),
                ('david', 'David Lee', 'david@example.com'),
                ('emma', 'Emma Thompson', 'emma@example.com'),
                ('frank', 'Frank Wilson', 'frank@example.com'),
                ('grace', 'Grace Kim', 'grace@example.com'),
                ('henry', 'Henry Brown', 'henry@example.com'),
                ('ivy', 'Ivy Chen', 'ivy@example.com'),
                ('jack', 'Jack Taylor', 'jack@example.com'),
            ]
            for username, full_name, email in customer_data:
                first_name, last_name = full_name.split(' ', 1)
                user = User.objects.create_user(
                    username=username,
                    email=email,
                    password='test123',
                    first_name=first_name,
                    last_name=last_name,
                    role=User.Role.CUSTOMER,
                )
                customers.append(user)
            self.stdout.write(f'Created {len(customer_data)} customer users')

        statuses = ['SCHEDULED', 'SCHEDULED', 'SCHEDULED', 'CONFIRMED', 'CONFIRMED', 'COMPLETED']

        # Get the current month range
        now = timezone.now()
        start_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        if now.month == 12:
            end_of_month = start_of_month.replace(year=now.year + 1, month=1)
        else:
            end_of_month = start_of_month.replace(month=now.month + 1)

        count = options['count']
        created = 0

        # Get content types for participants
        resource_ct = ContentType.objects.get_for_model(Resource)
        user_ct = ContentType.objects.get_for_model(User)

        self.stdout.write(f'Creating {count} appointments for {start_of_month.strftime("%B %Y")}...')

        for _ in range(count):
            # Random day in the month
            days_in_month = (end_of_month - start_of_month).days
            random_day = random.randint(0, days_in_month - 1)
            appointment_date = start_of_month + timedelta(days=random_day)

            # Random time between 8am and 6pm
            hour = random.randint(8, 17)
            minute = random.choice([0, 15, 30, 45])
            start_time = appointment_date.replace(hour=hour, minute=minute)

            # Skip if in the past and marked as scheduled
            status = random.choice(statuses)
            if start_time < now and status == 'SCHEDULED':
                status = 'COMPLETED'

            # Random service and duration
            service = random.choice(services)
            duration = service.duration

            # Random resource
            resource = random.choice(resources)

            # Random customer
            customer = random.choice(customers)

            # Create the event
            end_time = start_time + timedelta(minutes=duration)

            event = Event.objects.create(
                title=f'{customer.full_name} - {service.name}',
                start_time=start_time,
                end_time=end_time,
                status=status,
                notes=f'Service: {service.name}',
            )

            # Create participant for the resource
            Participant.objects.create(
                event=event,
                role=Participant.Role.RESOURCE,
                content_type=resource_ct,
                object_id=resource.id,
            )

            # Create participant for the customer
            Participant.objects.create(
                event=event,
                role=Participant.Role.CUSTOMER,
                content_type=user_ct,
                object_id=customer.id,
            )

            created += 1

        self.stdout.write(
            self.style.SUCCESS(f'Successfully created {created} demo appointments with resource and customer links')
        )
