from datetime import timedelta

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

from apps.disseminations.models import Channel, Campaign, Post

User = get_user_model()

CHANNELS = [
    ("CSIS Twitter", "twitter", "@CSIS_Indonesia", "https://twitter.com/CSIS_Indonesia"),
    ("CSIS Instagram", "instagram", "@csis.indonesia", "https://instagram.com/csis.indonesia"),
    ("CSIS LinkedIn", "linkedin", "csis-indonesia", "https://linkedin.com/company/csis-indonesia"),
    ("CSIS YouTube", "youtube", "@CSISIndonesia", "https://youtube.com/@CSISIndonesia"),
    ("CSIS Facebook", "facebook", "CSISIndonesia", "https://facebook.com/CSISIndonesia"),
]

CAMPAIGNS = [
    ("Indo-Pacific Outlook 2026", "Drive readership of the flagship report", "#2563eb"),
    ("Annual Conference 2026", "Boost event registrations", "#16a34a"),
    ("Economic Quarterly Series", "Sustained thought-leadership cadence", "#db2777"),
]

POSTS = [
    ("Indo-Pacific Outlook 2026 is live", "Our flagship report on regional security dynamics is out now. Read it free.", "published"),
    ("Join us at the Annual Conference", "Registration is open for CSIS Annual Conference 2026. Limited seats.", "scheduled"),
    ("Q1 Economic brief", "Inflation cooled to 2.8%. Full brief in thread below.", "published"),
    ("Webinar replay available", "Missed the panel on ASEAN trade? Watch the full recording.", "published"),
    ("Hiring: Research Associate", "We're looking for a Research Associate in Economics.", "draft"),
    ("Thread: 5 takeaways from the summit", "1/ Regional cooperation deepened...", "scheduled"),
    ("Op-ed in Kompas", "Our director's latest op-ed on fiscal policy.", "published"),
    ("Podcast episode 12", "This week: supply chains and resilience.", "archived"),
]


class Command(BaseCommand):
    help = "Seed dissemination channels, campaigns and scheduled/published posts."

    def add_arguments(self, parser):
        parser.add_argument("--clear", action="store_true", help="Delete existing dissemination data first")

    def handle(self, *args, **opts):
        if opts["clear"]:
            Post.objects.all().delete()
            Campaign.objects.all().delete()
            Channel.objects.all().delete()
            self.stdout.write("Cleared existing dissemination data.")

        user = User.objects.filter(is_superuser=True).first() or User.objects.first()
        now = timezone.now()

        channels = []
        for name, platform, handle, url in CHANNELS:
            ch, _ = Channel.objects.get_or_create(
                name=name, platform=platform,
                defaults={"handle": handle, "profile_url": url, "created_by": user},
            )
            channels.append(ch)

        campaigns = []
        for i, (name, objective, color) in enumerate(CAMPAIGNS):
            camp, _ = Campaign.objects.get_or_create(
                name=name,
                defaults={
                    "objective": objective, "color": color, "created_by": user,
                    "start_date": (now - timedelta(days=30)).date(),
                    "end_date": (now + timedelta(days=60)).date(),
                },
            )
            campaigns.append(camp)

        created = 0
        for i, (title, body, status) in enumerate(POSTS):
            if Post.objects.filter(title=title).exists():
                continue
            scheduled = now + timedelta(days=i) if status == "scheduled" else now - timedelta(days=i)
            post = Post.objects.create(
                title=title, body=body, status=status, author=user,
                campaign=campaigns[i % len(campaigns)],
                scheduled_at=scheduled,
                published_at=now - timedelta(days=i) if status == "published" else None,
                tags=["csis", "research"],
                metrics={"reach": (i + 1) * 1200, "likes": (i + 1) * 45, "shares": (i + 1) * 8} if status == "published" else {},
            )
            post.channels.set(channels[: (i % len(channels)) + 1])
            created += 1

        self.stdout.write(self.style.SUCCESS(
            f"Channels: {Channel.objects.count()}, campaigns: {Campaign.objects.count()}, posts: +{created}"
        ))
