"""Management command: migrate existing KB data into Content Engine.

Usage:
    python manage.py migrate_kb_to_content [--tenant <slug>] [--dry-run]
"""

from __future__ import annotations

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Migrate existing KB data (KBCategory, KBArticle, KBArticleVersion) to Content Engine"

    def add_arguments(self, parser):
        parser.add_argument("--tenant", type=str, help="Tenant slug (default: all active)")
        parser.add_argument("--dry-run", action="store_true", help="Preview changes without executing")

    def handle(self, *args, **options):
        from importlib.util import find_spec

        if find_spec("simorgh.apps.kb.models") is None:
            self.stdout.write(self.style.ERROR("KB app not found. Migration skipped."))
            return

        from simorgh.apps.tenants.models import Tenant

        tenant_slug = options.get("tenant")
        dry_run = options.get("dry_run", False)

        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

        stats = {"categories_migrated": 0, "categories_skipped": 0,
                 "articles_migrated": 0, "articles_skipped": 0,
                 "versions_created": 0}

        for tenant in tenants:
            self._migrate_tenant(tenant, stats, dry_run)

        if dry_run:
            self.stdout.write(self.style.SUCCESS(
                f"DRY RUN — would migrate: {stats['categories_migrated']} categories, "
                f"{stats['articles_migrated']} articles, {stats['versions_created']} versions"
            ))
        else:
            self.stdout.write(self.style.SUCCESS(
                f"Migrated: {stats['categories_migrated']} categories (skipped {stats['categories_skipped']}), "
                f"{stats['articles_migrated']} articles (skipped {stats['articles_skipped']}), "
                f"{stats['versions_created']} versions"
            ))

    def _migrate_tenant(self, tenant, stats: dict, dry_run: bool) -> None:
        from simorgh.apps.content.models import (
            ContentCategory,
            ContentItem,
            ContentStatus,
            ContentVisibility,
        )
        from simorgh.apps.kb.models import KBArticle, KBArticleVersion, KBCategory
        from simorgh.apps.organizations.models import OrganizationNode

        org = OrganizationNode.objects.filter(tenant=tenant).order_by("lft").first()
        if not org:
            return

        # 1. Migrate KB Categories → Content Categories
        kb_cats = list(KBCategory.objects.filter(tenant=tenant))
        cat_id_map: dict[int, int] = {}

        for kc in kb_cats:
            existing = ContentCategory.objects.filter(tenant=tenant, slug=kc.slug).first()
            if existing:
                cat_id_map[kc.pk] = existing.pk
                stats["categories_skipped"] += 1
                continue

            if dry_run:
                stats["categories_migrated"] += 1
                continue

            cat = ContentCategory.objects.create(
                tenant_id=tenant.pk,
                organization_node_id=org.pk,
                name=kc.name,
                slug=kc.slug,
                parent_id=cat_id_map.get(kc.parent_id),
                icon=kc.icon if hasattr(kc, "icon") else "",
                sort_order=kc.order if hasattr(kc, "order") else 0,
                is_active=True,
            )
            cat_id_map[kc.pk] = cat.pk
            stats["categories_migrated"] += 1

        # 2. Migrate KB Articles → Content Items
        kb_articles = KBArticle.objects.filter(tenant=tenant)

        for art in kb_articles:
            existing = ContentItem.objects.filter(tenant=tenant, slug=art.slug).first()
            if existing:
                stats["articles_skipped"] += 1
                continue

            if dry_run:
                stats["articles_migrated"] += 1
                continue

            # Map status
            status_map = {"draft": ContentStatus.DRAFT, "published": ContentStatus.PUBLISHED, "archived": ContentStatus.ARCHIVED}
            new_status = status_map.get(art.status, ContentStatus.DRAFT)

            # Map visibility
            vis_map = {"public": ContentVisibility.PUBLIC, "internal": ContentVisibility.INTERNAL, "private": ContentVisibility.PRIVATE}
            new_vis = vis_map.get(art.visibility, ContentVisibility.INTERNAL)

            item = ContentItem.objects.create(
                tenant_id=tenant.pk,
                organization_node_id=org.pk,
                title=art.title,
                slug=art.slug,
                content_type="kb_article",
                category_id=cat_id_map.get(art.category_id),
                body=art.body_html if hasattr(art, "body_html") else "",
                status=new_status,
                visibility=new_vis,
                author_id=art.author_id,
                published_at=art.published_at if hasattr(art, "published_at") else None,
                view_count=art.view_count if hasattr(art, "view_count") else 0,
                helpful_count=art.helpful_count if hasattr(art, "helpful_count") else 0,
                not_helpful_count=art.not_helpful_count if hasattr(art, "not_helpful_count") else 0,
            )
            stats["articles_migrated"] += 1

            # 3. Migrate KBArticleVersions → ContentVersions
            kb_versions = KBArticleVersion.objects.filter(article=art).order_by("version")
            for kv in kb_versions:
                from simorgh.apps.content.models import ContentVersion
                ContentVersion.objects.create(
                    tenant_id=tenant.pk,
                    organization_node_id=org.pk,
                    content_item=item,
                    version=kv.version,
                    title=art.title,
                    body=kv.body_html if hasattr(kv, "body_html") else "",
                    status=item.status,
                    changed_by_id=kv.changed_by_id if hasattr(kv, "changed_by_id") else None,
                    change_summary=kv.change_summary if hasattr(kv, "change_summary") else "",
                )
                stats["versions_created"] += 1

        self.stdout.write(f"  Tenant {tenant.slug}: {stats['categories_migrated']} cats, {stats['articles_migrated']} articles")
