"""`python manage.py seed_workspaces` — provision canonical workspaces.

Seeds (or re-seeds) the standard workspace catalogue defined in
``simorgh.apps.workspaces.workspace_seeds`` for one or all tenants.
All operations are idempotent — safe to run multiple times.

Usage::

    # Seed all tenants
    python manage.py seed_workspaces

    # Seed a specific tenant
    python manage.py seed_workspaces --tenant momenin

    # Dry-run: show what would be created without writing anything
    python manage.py seed_workspaces --dry-run
"""

from __future__ import annotations

from django.core.management.base import BaseCommand, CommandError

from simorgh.apps.tenants.models import Tenant
from simorgh.apps.workspaces.workspace_seeds import WORKSPACE_CATALOG, seed_workspaces_for_tenant


class Command(BaseCommand):
    help = "Seed canonical workspaces and roles for one or all tenants (idempotent)."

    def add_arguments(self, parser):
        parser.add_argument(
            "--tenant",
            metavar="SLUG",
            help="Seed only this tenant (by slug). Omit to seed all active tenants.",
        )
        parser.add_argument(
            "--dry-run",
            action="store_true",
            default=False,
            help="Print what would be created without writing to the database.",
        )

    def handle(self, *args, **options):
        tenant_slug = options.get("tenant")
        dry_run: bool = options["dry_run"]

        if dry_run:
            self._print_plan()
            return

        if tenant_slug:
            try:
                tenants = [Tenant.objects.get(slug=tenant_slug)]
            except Tenant.DoesNotExist:
                raise CommandError(f"Tenant {tenant_slug!r} not found.")
        else:
            tenants = list(Tenant.objects.all().order_by("slug"))

        if not tenants:
            self.stdout.write(self.style.WARNING("No tenants found — nothing to seed."))
            return

        total_ws_created = 0
        total_role_created = 0
        total_grant_created = 0

        for tenant in tenants:
            self.stdout.write(f"\nTenant: {self.style.MIGRATE_HEADING(tenant.slug)}")
            result = seed_workspaces_for_tenant(tenant)

            if result.get("status") == "skipped":
                self.stdout.write(
                    self.style.WARNING(
                        f"  ⚠ Skipped ({result.get('reason', 'unknown')})"
                    )
                )
                continue

            for ws in result.get("workspaces", []):
                ws_label = f"  Workspace [{ws['slug']}]"
                if ws["created"]:
                    ws_label += self.style.SUCCESS(" ✓ created")
                    total_ws_created += 1
                else:
                    ws_label += " (already exists)"
                self.stdout.write(ws_label)

                for r in ws.get("roles", []):
                    role_label = f"    Role [{r['code']}]"
                    if r["role_created"]:
                        role_label += self.style.SUCCESS(" ✓ created")
                        total_role_created += 1
                    else:
                        role_label += " (already exists)"
                    grant_label = ""
                    if r["grant_created"]:
                        grant_label = self.style.SUCCESS(" → grant ✓")
                        total_grant_created += 1
                    else:
                        grant_label = " → grant (exists)"
                    self.stdout.write(role_label + grant_label)

        self.stdout.write(
            "\n"
            + self.style.SUCCESS(
                f"Done. {total_ws_created} workspace(s), "
                f"{total_role_created} role(s), "
                f"{total_grant_created} grant(s) created."
            )
        )

    def _print_plan(self):
        """Print the workspace+role catalogue without touching the DB."""
        self.stdout.write(self.style.MIGRATE_HEADING("\nWorkspace seed plan (dry-run):"))
        for ws_spec in WORKSPACE_CATALOG:
            self.stdout.write(f"\n  Workspace: {ws_spec['slug']} — {ws_spec['name']}")
            for role_spec in ws_spec["roles"]:
                perms = role_spec.get("permissions", [])
                self.stdout.write(
                    f"    Role: {role_spec['code']} ({role_spec['name']})"
                    f" — {len(perms)} permissions"
                )
