import random
from datetime import timedelta

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone

from opcalendar.models import Event, EventCategory, EventHost, EventVisibility

FLEET_NAMES = [
    "Stratop: Hostile Staging Cleanup",
    "Roaming Gang - Null Sec",
    "Mining Op - Moon Goo",
    "CTA: Defend Home System",
    "Training Op - New Bros Welcome",
    "Black Ops Drop",
    "Capital Escalation Response",
    "Faction Warfare Plex Run",
    "Industry Op - Hauling Run",
    "PvP Roam - Lowsec",
]

DOCTRINES = [
    "https://example.com/doctrine/armor-cruiser",
    "https://example.com/doctrine/shield-bs",
    "Whatever you've got, T1 frigates",
    "https://example.com/doctrine/capital-escalation",
    "Logistics + DPS, see doctrine sheet",
]

SYSTEMS = [
    "Jita",
    "Amarr",
    "Rens",
    "Dodixie",
    "Hek",
    "1DQ1-A",
    "Tama",
    "Rancer",
    "EC-P8R",
    "Vlillirier",
]

FCS = [
    "Some FC",
    "Another FC",
    "Fleet Boss",
    "Capital Pilot",
    "Newbro Friendly FC",
]

DESCRIPTIONS = [
    "Form up on time, bring your A-game.",
    "Casual roam, all are welcome.",
    "Mandatory attendance for corp members.",
    "Bring scout alts if you have them.",
    "Doctrine fit only, check fitting in description.",
]

# Non-custom timings only, so we don't need to also set notification_custom_date
NOTIFICATION_TIMING_POOL = [
    Event.NOTIFY_NOW,
    Event.NOTIFY_1H_BEFORE,
    Event.NOTIFY_1D_BEFORE,
    Event.NOTIFY_1W_BEFORE,
]

# name, ticker, color, icon
CATEGORIES = [
    ("Stratop", "OP", "#e74c3c", "fas fa-rocket"),
    ("Mining", "MIN", "#27ae60", "fas fa-cubes"),
    ("CTA", "CTA", "#c0392b", "fas fa-exclamation-triangle"),
    ("Roam", "ROAM", "#2980b9", "fas fa-route"),
    ("Training", "TRN", "#8e44ad", "fas fa-graduation-cap"),
    ("Industry", "IND", "#f39c12", "fas fa-industry"),
    ("Social", "SOC", "#16a085", "fas fa-glass-cheers"),
]


class Command(BaseCommand):
    help = (
        "Creates a number of random example events on the calendar for "
        "testing/demo purposes. Creates a default host/category/visibility "
        "filter if none exist yet."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "count",
            nargs="?",
            type=int,
            default=10,
            help="Number of random events to create (default: 10)",
        )

    def handle(self, *args, **options):
        count = options["count"]

        host, _ = EventHost.objects.get_or_create(
            community="Example Host",
            defaults={"is_default": True},
        )

        categories = []
        for name, ticker, color, icon in CATEGORIES:
            category, _ = EventCategory.objects.get_or_create(
                name=name,
                defaults={
                    "ticker": ticker,
                    "color": color,
                    "icon": icon,
                },
            )
            categories.append(category)

        visibility, _ = EventVisibility.objects.get_or_create(
            name="Public",
            defaults={"is_default": True, "is_visible": True},
        )

        user = User.objects.filter(is_superuser=True).first() or User.objects.first()
        if not user:
            self.stderr.write(
                self.style.ERROR(
                    "No users found in the database - create a user first."
                )
            )
            return

        profile = getattr(user, "profile", None)
        character = getattr(profile, "main_character", None)

        now = timezone.now()
        created = 0

        for i in range(count):
            start_offset = timedelta(
                days=random.randint(-3, 21),
                hours=random.randint(0, 23),
                minutes=random.choice([0, 15, 30, 45]),
            )
            start_time = (now + start_offset).replace(second=0, microsecond=0)
            end_time = start_time + timedelta(hours=random.choice([1, 2, 3, 4]))

            notification_timings = random.sample(
                NOTIFICATION_TIMING_POOL,
                k=random.randint(1, 2),
            )

            Event.objects.create(
                operation_type=random.choice(categories),
                title=f"{random.choice(FLEET_NAMES)} #{i + 1}",
                host=host,
                doctrine=random.choice(DOCTRINES),
                formup_system=random.choice(SYSTEMS),
                description=random.choice(DESCRIPTIONS),
                start_time=start_time,
                end_time=end_time,
                fc=random.choice(FCS),
                event_visibility=visibility,
                important=random.random() < 0.15,
                notification_timings=notification_timings,
                eve_character=character,
                user=user,
            )
            created += 1

        self.stdout.write(self.style.SUCCESS(f"Created {created} random events."))
