"""`python manage.py seed_kb` — idempotent KB seed.

Seeds demo KB data into the demo tenant:
  - "General" root category
  - "Getting Started" (published) article
  - "Troubleshooting" sub-category

Re-running is safe: all steps use get_or_create.
"""

from __future__ import annotations

from typing import Any

from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import transaction

from simorgh.apps.kb.models import ArticleStatus, ArticleVisibility, KBArticle, KBArticleVersion, KBCategory
from simorgh.apps.tenants.models import Tenant


TENANT_SLUG = "solan"


class Command(BaseCommand):
    help = "Seed demo KB categories and articles for the demo tenant (idempotent)."

    def handle(self, *args: Any, **options: Any) -> None:
        try:
            tenant = Tenant.objects.get(slug=TENANT_SLUG)
        except Tenant.DoesNotExist:
            self.stderr.write(
                self.style.ERROR(
                    f"Tenant '{TENANT_SLUG}' not found. Run seed_dev first."
                )
            )
            return

        with transaction.atomic():
            author = get_user_model().objects.filter(is_superuser=True).first()
            self._seed(tenant, author)

        self.stdout.write(self.style.SUCCESS("KB seed complete."))

    def _seed(self, tenant: Tenant, author: Any) -> None:
        # ── Root category: General ──────────────────────────────────────────
        general, created = KBCategory.objects.get_or_create(
            tenant=tenant,
            slug="general",
            defaults={
                "name": "General",
                "icon": "📖",
                "order": 0,
                "parent": None,
            },
        )
        if created:
            self.stdout.write(f"  Created category: {general.name}")
        else:
            self.stdout.write(f"  Category exists: {general.name}")

        # ── Sub-category: Troubleshooting ───────────────────────────────────
        troubleshooting, created = KBCategory.objects.get_or_create(
            tenant=tenant,
            slug="troubleshooting",
            defaults={
                "name": "Troubleshooting",
                "icon": "🔧",
                "order": 1,
                "parent": general,
            },
        )
        if created:
            self.stdout.write(f"  Created category: {troubleshooting.name}")
        else:
            self.stdout.write(f"  Category exists: {troubleshooting.name}")

        # ── Article: Getting Started ────────────────────────────────────────
        article, created = KBArticle.objects.get_or_create(
            tenant=tenant,
            slug="getting-started",
            defaults={
                "title": "Getting Started",
                "status": ArticleStatus.PUBLISHED,
                "visibility": ArticleVisibility.PUBLIC,
                "category": general,
                "author": author,
                "body_html": (
                    "<h2>Welcome to the Knowledge Base</h2>"
                    "<p>This is the getting started article. Edit it to provide "
                    "helpful information for your users.</p>"
                    "<h3>Quick Tips</h3>"
                    "<ul>"
                    "<li>Browse categories on the left sidebar</li>"
                    "<li>Use the search bar to find articles quickly</li>"
                    "<li>Mark articles as helpful using the thumbs up/down buttons</li>"
                    "</ul>"
                ),
            },
        )
        if created:
            self.stdout.write(f"  Created article: {article.title}")
            # Create initial version snapshot
            KBArticleVersion.objects.create(
                article=article,
                version=1,
                body_html=article.body_html,
                change_summary="Initial version",
                changed_by=None,
            )
        else:
            self.stdout.write(f"  Article exists: {article.title}")

        # ── Article: FAQ ────────────────────────────────────────────────────
        faq, created = KBArticle.objects.get_or_create(
            tenant=tenant,
            slug="faq",
            defaults={
                "title": "Frequently Asked Questions",
                "status": ArticleStatus.DRAFT,
                "visibility": ArticleVisibility.PUBLIC,
                "category": general,
                "author": author,
                "body_html": (
                    "<h2>Frequently Asked Questions</h2>"
                    "<p>Coming soon. Please check back later.</p>"
                ),
            },
        )
        if created:
            self.stdout.write(f"  Created article: {faq.title}")
        else:
            self.stdout.write(f"  Article exists: {faq.title}")
