from django.core.management.base import BaseCommand
from django.conf import settings
from apps.users.models import User, RegistrationDomainRule, RegistrationRestrictionSetting
from apps.events.models import Skill, Event, TaskArea, Shift, ShiftSignup, EventTemplate
from apps.branding.models import BrandingSetting

class Command(BaseCommand):
    help = "Populate database with initial demo data including Demo Admin & Demo User"

    def handle(self, *args, **options):
        if not settings.DEBUG:
            self.stdout.write(self.style.WARNING("seed_data wird im Produktionsmodus (DEBUG=False) übersprungen."))
            return

        # 1. Branding
        branding = BrandingSetting.get_solo()
        branding.app_name = "Veranstaltungsschichtplaner (Dev)"
        branding.custom_banner_text = "💡 DEV INSTANZ: Demo Admin (admin / adminpassword) & Demo User (demouser / demouser123)"
        branding.save()

        # 2. Skills
        skill_ersthelfer, _ = Skill.objects.get_or_create(
            name="Ersthelfer",
            defaults={'description': 'Gültiger Erste-Hilfe-Schein', 'color': '#ef4444'}
        )
        skill_bar, _ = Skill.objects.get_or_create(
            name="Bar-Erfahrung",
            defaults={'description': 'Erfahrung an der Zapfanlage', 'color': '#3b82f6'}
        )
        skill_fuehrerschein, _ = Skill.objects.get_or_create(
            name="Führerschein B",
            defaults={'description': 'PKW / Transporter fahren', 'color': '#10b981'}
        )

        # 3. Demo Admin User
        admin_user, admin_created = User.objects.get_or_create(
            username='admin',
            defaults={
                'email': 'admin@demo.local',
                'display_name': 'Demo Admin',
                'is_admin_user': True,
                'is_staff': True,
                'is_superuser': True
            }
        )
        if admin_created:
            admin_user.set_password('adminpassword')
            admin_user.save()
            self.stdout.write(self.style.SUCCESS("Demo Admin created: admin / adminpassword"))
        else:
            admin_user.set_password('adminpassword')
            admin_user.is_admin_user = True
            admin_user.is_staff = True
            admin_user.is_superuser = True
            admin_user.save()

        # 4. Demo Regular User
        demo_user, user_created = User.objects.get_or_create(
            username='demouser',
            defaults={
                'email': 'user@demo.local',
                'display_name': 'Demo User',
                'is_admin_user': False
            }
        )
        if user_created:
            demo_user.set_password('demouser123')
            demo_user.save()
            demo_user.skills.add(skill_bar, skill_ersthelfer)
            self.stdout.write(self.style.SUCCESS("Demo User created: demouser / demouser123"))
        else:
            demo_user.set_password('demouser123')
            demo_user.save()
            demo_user.skills.add(skill_bar, skill_ersthelfer)

        # 5. Sample Event with Task Areas & Shifts
        if not Event.objects.filter(title="Sommerfest 2026").exists():
            event = Event.objects.create(
                title="Sommerfest 2026",
                description="Großes Vereins-Sommerfest mit Musik, Essen und Kinderprogramm",
                location="Vereinsgelände, Festwiese",
                start_date="2026-08-15",
                end_date="2026-08-16",
                created_by=admin_user
            )

            # Task Area: Tresendienst
            ta_tresen = TaskArea.objects.create(
                event=event, name="Tresendienst", description="Getränke- & Barverkauf", order=1
            )
            s1 = Shift.objects.create(
                task_area=ta_tresen, title="Nachmittagsschicht", start_time="14:00", end_time="18:00", max_participants=3
            )
            s1.required_skills.add(skill_bar)
            # Demo signup for demo_user
            ShiftSignup.objects.create(shift=s1, user=demo_user)

            s2 = Shift.objects.create(
                task_area=ta_tresen, title="Abendschicht", start_time="18:00", end_time="23:00", max_participants=4
            )

            # Task Area: Essen kochen
            ta_essen = TaskArea.objects.create(
                event=event, name="Essen kochen & Stand", description="Grill & Salatausgabe", order=2
            )
            Shift.objects.create(
                task_area=ta_essen, title="Vorbereitung & Grillen", start_time="11:30", end_time="16:00", max_participants=3
            )
            Shift.objects.create(
                task_area=ta_essen, title="Abendschicht Essen", start_time="16:00", end_time="21:00", max_participants=3
            )

            # Task Area: Aufbau & Aufräumen
            ta_aufbau = TaskArea.objects.create(
                event=event, name="Aufbau & Aufräumen", description="Bänke, Pavillons & Technik", order=3
            )
            s_aufbau = Shift.objects.create(
                task_area=ta_aufbau, title="Früher Aufbau", start_time="09:00", end_time="13:00", max_participants=5
            )
            s_aufbau.required_skills.add(skill_fuehrerschein)

            Shift.objects.create(
                task_area=ta_aufbau, title="Nacht-Aufräumen", start_time="23:00", end_time="01:00", max_participants=4
            )

            self.stdout.write(self.style.SUCCESS("Sample Event 'Sommerfest 2026' created."))

        # 6. Sample Template
        if not EventTemplate.objects.filter(name="Standard Vereinsfest Template").exists():
            EventTemplate.objects.create(
                name="Standard Vereinsfest Template",
                description="Standard-Struktur mit Tresendienst, Essen kochen sowie Aufbau & Aufräumen",
                template_data={
                    "task_areas": [
                        {
                            "name": "Tresendienst",
                            "description": "Getränkezapfen und Verkauf",
                            "order": 1,
                            "shifts": [
                                {"title": "Frühschicht", "start_time": "12:00", "end_time": "17:00", "max_participants": 2, "required_skill_names": ["Bar-Erfahrung"]},
                                {"title": "Spätschicht", "start_time": "17:00", "end_time": "22:00", "max_participants": 3}
                            ]
                        },
                        {
                            "name": "Essen kochen",
                            "description": "Zubereitung & Verpflegung",
                            "order": 2,
                            "shifts": [
                                {"title": "Mittagessen", "start_time": "11:00", "end_time": "15:00", "max_participants": 3}
                            ]
                        },
                        {
                            "name": "Aufbau & Aufräumen",
                            "description": "Aufbau und Abbau der Infrastruktur",
                            "order": 3,
                            "shifts": [
                                {"title": "Gesamtaufbau", "start_time": "08:00", "end_time": "12:00", "max_participants": 4}
                            ]
                        }
                    ]
                },
                created_by=admin_user
            )

        self.stdout.write(self.style.SUCCESS("Dev seed data populated with Demo Admin & Demo User!"))
