"""Management command: seed default content categories."""

from __future__ import annotations

from django.core.management.base import BaseCommand
from django.db import transaction

from simorgh.apps.content.models import ContentCategory

DEFAULT_CATEGORIES = [
    {"name": "Knowledge Base", "slug": "knowledge-base", "icon": "book", "children": [
        {"name": "Getting Started", "slug": "getting-started", "icon": "rocket"},
        {"name": "Troubleshooting", "slug": "troubleshooting", "icon": "wrench"},
        {"name": "Best Practices", "slug": "best-practices", "icon": "star"},
    ]},
    {"name": "Documentation", "slug": "documentation", "icon": "file-text", "children": [
        {"name": "Developer Docs", "slug": "developer-docs", "icon": "code"},
        {"name": "User Manuals", "slug": "user-manuals", "icon": "help-circle"},
        {"name": "Admin Manuals", "slug": "admin-manuals", "icon": "settings"},
        {"name": "Architecture", "slug": "architecture", "icon": "layers"},
        {"name": "API Reference", "slug": "api-reference", "icon": "terminal"},
    ]},
    {"name": "Policies", "slug": "policies", "icon": "shield", "children": [
        {"name": "Security Policies", "slug": "security-policies", "icon": "lock"},
        {"name": "HR Policies", "slug": "hr-policies", "icon": "users"},
        {"name": "IT Policies", "slug": "it-policies", "icon": "monitor"},
    ]},
    {"name": "Procedures", "slug": "procedures", "icon": "clipboard", "children": [
        {"name": "Onboarding", "slug": "onboarding", "icon": "user-plus"},
        {"name": "Offboarding", "slug": "offboarding", "icon": "user-minus"},
        {"name": "Incident Response", "slug": "incident-response", "icon": "alert-triangle"},
    ]},
    {"name": "News & Announcements", "slug": "news-announcements", "icon": "megaphone", "children": [
        {"name": "Company News", "slug": "company-news", "icon": "newspaper"},
        {"name": "Release Notes", "slug": "release-notes", "icon": "tag"},
        {"name": "Changelogs", "slug": "changelogs", "icon": "git-commit"},
    ]},
    {"name": "FAQs", "slug": "faqs", "icon": "message-circle"},
]


class Command(BaseCommand):
    help = "Seed default content categories for all active tenants"

    def add_arguments(self, parser):
        parser.add_argument("--tenant", type=str, help="Tenant slug to seed (default: all active)")

    @transaction.atomic
    def handle(self, *args, **options):
        from simorgh.apps.organizations.models import OrganizationNode
        from simorgh.apps.tenants.models import Tenant

        tenant_slug = options.get("tenant")
        if tenant_slug:
            tenants = Tenant.objects.filter(slug=tenant_slug, status="active")
        else:
            tenants = Tenant.objects.filter(status="active")

        if not tenants:
            self.stdout.write(self.style.WARNING("No active tenants found."))
            return

        created_total = 0
        for tenant in tenants:
            org = OrganizationNode.objects.filter(tenant=tenant).order_by("lft").first()
            if not org:
                self.stdout.write(self.style.WARNING(f"No org node for tenant {tenant.slug}"))
                continue

            created = self._seed_categories(tenant.pk, org.pk, DEFAULT_CATEGORIES)
            created_total += created

        self.stdout.write(self.style.SUCCESS(f"Seeded {created_total} categories across {len(tenants)} tenant(s)."))

    def _seed_categories(self, tenant_id: int, org_id: int, entries: list[dict], parent_id: int | None = None) -> int:
        count = 0
        for entry in entries:
            cat, created = ContentCategory.objects.get_or_create(
                tenant_id=tenant_id,
                slug=entry["slug"],
                defaults={
                    "name": entry["name"],
                    "organization_node_id": org_id,
                    "parent_id": parent_id,
                    "icon": entry.get("icon", ""),
                    "is_active": True,
                },
            )
            if created:
                count += 1
            children = entry.get("children", [])
            if children:
                count += self._seed_categories(tenant_id, org_id, children, cat.pk)
        return count
