"""Management command: seed_subscriptions

Creates TenantSubscription rows for all active tenants that don't yet have one.
Uses the tenant's legacy ``plan_ref`` field to determine the plan, falling back
to "starter" when not set or when the plan_ref value doesn't match a known plan.

Also seeds example TenantAddonFeature rows for the acme/enterprise tenant.

Usage:
    python manage.py seed_subscriptions
    python manage.py seed_subscriptions --plan enterprise  # override plan for all
"""

from __future__ import annotations

import logging

from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone

logger = logging.getLogger(__name__)

# Map from legacy plan_ref values to Plan codes
_PLAN_REF_MAP = {
    "free": "free",
    "starter": "starter",
    "standard": "starter",      # legacy alias
    "basic": "starter",         # legacy alias
    "business": "business",
    "professional": "business", # legacy alias
    "enterprise": "enterprise",
    "custom": "enterprise",
}

# Sample add-on features for demo/enterprise tenants
DEMO_ADDONS = [
    {"feature_key": "ai.ai_assistant", "price_paid": "0"},
    {"feature_key": "dms.ai_tagging", "price_paid": "0"},
]


class Command(BaseCommand):
    help = "Seed TenantSubscription rows for all active tenants."

    def add_arguments(self, parser):
        parser.add_argument(
            "--plan",
            type=str,
            default=None,
            help="Override plan code for all tenants (free|starter|business|enterprise).",
        )
        parser.add_argument(
            "--seed-addons",
            action="store_true",
            default=False,
            help="Also seed demo TenantAddonFeature rows for enterprise tenants.",
        )

    @transaction.atomic
    def handle(self, *args, **options):
        from simorgh.apps.subscription.models import (
            PlatformPlan,
            TenantAddonFeature,
            TenantSubscription,
        )
        from simorgh.apps.tenants.models import Tenant

        force_plan = options.get("plan")
        seed_addons = options.get("seed_addons", False)

        tenants = Tenant.objects.filter(status="active").order_by("slug")
        created_count = 0
        skipped_count = 0

        for tenant in tenants:
            if TenantSubscription.objects.filter(tenant=tenant).exists():
                self.stdout.write(f"  → {tenant.slug}: already has subscription — skipped")
                skipped_count += 1
                continue

            # Determine plan code
            if force_plan:
                plan_code = force_plan
            else:
                legacy_ref = getattr(tenant, "plan_ref", "") or ""
                ref_lower = legacy_ref.lower()
                # 1) Try the tenant's plan_ref directly (allows custom plans like "tmp")
                if PlatformPlan.objects.filter(code=ref_lower, is_active=True).exists():
                    plan_code = ref_lower
                # 2) Try the legacy mapping table
                elif ref_lower in _PLAN_REF_MAP:
                    plan_code = _PLAN_REF_MAP[ref_lower]
                # 3) Unknown → fall back to the most restricted plan
                else:
                    plan_code = "free"

            plan = PlatformPlan.objects.filter(code=plan_code, is_active=True).first()
            if plan is None:
                # fallback to free (most restricted plan)
                plan = PlatformPlan.objects.filter(code="free", is_active=True).first()
                if plan is None:
                    self.stdout.write(
                        self.style.ERROR(
                            f"  ✗ {tenant.slug}: no active plan found — run seed_plans first"
                        )
                    )
                    continue
                plan_code = "free"

            now = timezone.now()
            # Tenant needs an org node for TenantScopedModel
            from simorgh.apps.organizations.models import OrganizationNode
            org_node = OrganizationNode.objects.filter(tenant=tenant).order_by("depth", "pk").first()
            if org_node is None:
                self.stdout.write(
                    self.style.WARNING(
                        f"  ⚠ {tenant.slug}: no org node — subscription not seeded"
                    )
                )
                continue

            sub = TenantSubscription.objects.create(
                tenant=tenant,
                organization_node=org_node,
                plan=plan,
                status="active",
                current_period_start=now,
                current_period_end=now.replace(year=now.year + 1),
                seat_count=plan.user_limit if plan.user_limit > 0 else 100,
            )
            created_count += 1
            self.stdout.write(
                self.style.SUCCESS(
                    f"  ✓ {tenant.slug}: created subscription on plan '{plan_code}' (pk={sub.pk})"
                )
            )

            # Seed demo add-ons for enterprise tenants
            if seed_addons and plan_code in ("enterprise", "custom"):
                for addon_data in DEMO_ADDONS:
                    TenantAddonFeature.objects.get_or_create(
                        tenant=tenant,
                        feature_key=addon_data["feature_key"],
                        defaults={
                            "organization_node": org_node,
                            "purchased_at": now,
                            "price_paid": addon_data["price_paid"],
                            "is_active": True,
                        },
                    )
                self.stdout.write(
                    f"    + seeded {len(DEMO_ADDONS)} demo add-on features"
                )

        self.stdout.write(
            self.style.SUCCESS(
                f"\nDone. Subscriptions: {created_count} created, {skipped_count} skipped."
            )
        )
