"""Management command: dms_seed

Seeds DMS default document types for one or all tenants.

Usage
-----
  # Seed all tenants
  python manage.py dms_seed

  # Seed a specific tenant by slug
  python manage.py dms_seed --tenant acme

  # Dry-run — show what would be created without persisting
  python manage.py dms_seed --dry-run
"""

from __future__ import annotations

from django.core.management.base import BaseCommand, CommandError

from simorgh.apps.dms.seed_data import DEFAULT_DOCUMENT_TYPES


class Command(BaseCommand):
    help = "Seed DMS default document types for one or all tenants."

    def add_arguments(self, parser):
        parser.add_argument(
            "--tenant",
            dest="tenant_slug",
            default=None,
            help="Slug of the tenant to seed. Omit to seed all tenants.",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            dest="dry_run",
            default=False,
            help="Print what would be created without persisting.",
        )

    def handle(self, *args, **options):
        from simorgh.apps.tenants.models import Tenant

        tenant_slug = options["tenant_slug"]
        dry_run = options["dry_run"]

        if tenant_slug:
            try:
                tenants = [Tenant.objects.get(slug=tenant_slug)]
            except Tenant.DoesNotExist:
                raise CommandError(f"Tenant with slug {tenant_slug!r} not found.")
        else:
            tenants = list(Tenant.objects.filter(is_active=True))

        if not tenants:
            self.stdout.write(self.style.WARNING("No active tenants found."))
            return

        total_created = 0
        total_skipped = 0

        for tenant in tenants:
            created, skipped = self._seed_tenant(tenant, dry_run=dry_run)
            total_created += created
            total_skipped += skipped
            self.stdout.write(
                f"  Tenant [{tenant.slug}]: "
                f"{self.style.SUCCESS(f'{created} created')}, "
                f"{skipped} skipped"
            )

        summary = (
            f"\nDone. Total: {total_created} created, {total_skipped} skipped."
        )
        if dry_run:
            summary += " (DRY RUN — nothing persisted)"
        self.stdout.write(self.style.SUCCESS(summary))

    def _seed_tenant(self, tenant, *, dry_run: bool) -> tuple[int, int]:
        """Seed default document types for a single tenant.

        Returns
        -------
        (created_count, skipped_count)
        """
        from simorgh.apps.dms.documents.models import DocumentType
        from simorgh.apps.organizations.models import OrganizationNode

        root_node = (
            OrganizationNode.objects.filter(tenant=tenant, parent__isnull=True)
            .order_by("id")
            .first()
        )
        if root_node is None:
            self.stderr.write(
                self.style.WARNING(
                    f"  Tenant [{tenant.slug}]: no root org node — skipping."
                )
            )
            return 0, 0

        created = 0
        skipped = 0

        for spec in DEFAULT_DOCUMENT_TYPES:
            exists = DocumentType.objects.filter(
                tenant=tenant,
                code=spec["code"],
                is_deleted=False,
            ).exists()

            if exists:
                skipped += 1
                continue

            if not dry_run:
                DocumentType.objects.create(
                    tenant=tenant,
                    organization_node=root_node,
                    code=spec["code"],
                    name=spec["name"],
                    description=spec["description"],
                    icon=spec["icon"],
                    color=spec["color"],
                    is_active=True,
                )
            created += 1

        return created, skipped
