"""Management command: seed_plans

Creates or updates the default Plan records and their PlanEntitlement
mappings according to the Simorgh licensing model.

Usage:
    python manage.py seed_plans
    python manage.py seed_plans --reset   # deletes existing plan_features first
"""

from __future__ import annotations

from django.core.management.base import BaseCommand
from django.db import transaction

from simorgh.apps.subscription.models import PlanFeature, PlatformPlan

# ---------------------------------------------------------------------------
# Plan definitions
# ---------------------------------------------------------------------------

PLANS = [
    {
        "code": "free",
        "name": "Free",
        "description": "رایگان — برای تیم‌های کوچک تا ۳ نفر",
        "price_monthly": "0",
        "price_yearly": "0",
        "currency": "IRR",
        "user_limit": 3,
        "storage_gb": 1,
        "workflow_limit": 5,
        "api_calls_per_month": 1000,
        "trial_days": 0,
        "is_public": True,
        "is_active": True,
        "sort_order": 0,
    },
    {
        "code": "starter",
        "name": "Starter",
        "description": "پایه — برای کسب‌وکارهای کوچک تا ۱۰ نفر",
        "price_monthly": "2900000",
        "price_yearly": "29000000",
        "currency": "IRR",
        "user_limit": 10,
        "storage_gb": 20,
        "workflow_limit": 50,
        "api_calls_per_month": 50000,
        "trial_days": 14,
        "is_public": True,
        "is_active": True,
        "sort_order": 1,
    },
    {
        "code": "business",
        "name": "Business",
        "description": "کسب‌وکار — برای شرکت‌های متوسط تا ۵۰ نفر",
        "price_monthly": "7900000",
        "price_yearly": "79000000",
        "currency": "IRR",
        "user_limit": 50,
        "storage_gb": 100,
        "workflow_limit": -1,
        "api_calls_per_month": 500000,
        "trial_days": 14,
        "is_public": True,
        "is_active": True,
        "sort_order": 2,
    },
    {
        "code": "pro",
        "name": "Professional",
        "description": "حرفه‌ای — برای تیم‌های رو به رشد تا ۲۰۰ نفر",
        "price_monthly": "14900000",
        "price_yearly": "149000000",
        "currency": "IRR",
        "user_limit": 200,
        "storage_gb": 500,
        "workflow_limit": -1,
        "api_calls_per_month": 2000000,
        "trial_days": 14,
        "is_public": True,
        "is_active": True,
        "sort_order": 3,
    },
    {
        "code": "enterprise",
        "name": "Enterprise",
        "description": "سازمانی — نامحدود، همه ویژگی‌ها",
        "price_monthly": "0",
        "price_yearly": "0",
        "currency": "IRR",
        "user_limit": -1,
        "storage_gb": -1,
        "workflow_limit": -1,
        "api_calls_per_month": -1,
        "trial_days": 30,
        "is_public": True,
        "is_active": True,
        "sort_order": 4,
    },
    {
        "code": "custom",
        "name": "Custom",
        "description": "سفارشی — برای قراردادهای خاص",
        "price_monthly": "0",
        "price_yearly": "0",
        "currency": "IRR",
        "user_limit": -1,
        "storage_gb": -1,
        "workflow_limit": -1,
        "api_calls_per_month": -1,
        "trial_days": 0,
        "is_public": False,
        "is_active": True,
        "sort_order": 4,
    },
]

# ---------------------------------------------------------------------------
# Feature key sets per plan  (keys match {module_name}.{feature_code})
# ---------------------------------------------------------------------------

FREE_FEATURES = [
    # Collaboration
    "chat.direct_messaging",
    "chat.file_sharing",
    "calendar.event_management",
    "calendar.attendee_management",
    # Basic DMS
    "dms.document_storage",
    "dms.versioning",
    # Platform engines — basic services always available
    "delegations.rule_management",
    "assignments.assignment_management",
    "content.item_management",
    "catalog.item_management",
    "correspondence.letter_management",
]

STARTER_FEATURES = FREE_FEATURES + [
    # CRM — core
    "crm.contact_management",
    "crm.pipeline_management",
    "crm.lead_management",
    "crm.opportunity_management",
    "crm.activity_logging",
    # HR — core
    "hr.employee_records",
    "hr.employee_self_service",
    "hr.org_chart",
    # Knowledge Base
    "kb.article_management",
    "kb.article_publishing",
    "kb.category_taxonomy",
    "kb.visibility_control",
    # DMS — more
    "dms.preview",
    "dms.search",
    # Calendar — team
    "calendar.team_calendar",
    "calendar.event_linking",
    # Chat — search
    "chat.message_search",
]

BUSINESS_FEATURES = STARTER_FEATURES + [
    # CRM — advanced
    "crm.contact_merge",
    "crm.contact_export",
    "crm.lead_auto_assign",
    # HR — advanced
    "hr.leave_management",
    "hr.attendance_tracking",
    "hr.shift_management",
    "hr.document_management",
    # Projects
    "projects.project_management",
    "projects.project_phases",
    "projects.milestones",
    "projects.team_management",
    # Tasks
    "tasks.task_management",
    "tasks.subtasks",
    "tasks.task_comments",
    "tasks.task_attachments",
    "tasks.task_watchers",
    "tasks.task_templates",
    "tasks.kanban_view",
    # Helpdesk
    "helpdesk.ticket_management",
    "helpdesk.ticket_automation",
    "helpdesk.sla_management",
    "helpdesk.agent_teams",
    "helpdesk.multi_queue",
    "helpdesk.customer_portal",
    # BPM — core
    "bpm.pcf_framework",
    "bpm.process_definition",
    "bpm.raci_matrix",
    "bpm.kpi_management",
    "bpm.process_execution",
    # Time Tracking
    "time_tracking.time_logging",
    "time_tracking.time_approval",
    "time_tracking.time_reports",
    # DMS — collaboration
    "dms.collaboration",
    "dms.records_management",
    # Automation — basic
    "automation.rule_engine",
    "automation.webhooks",
    # KB — feedback
    "kb.article_feedback",
    # Escalation
    "escalation_engine.rule_management",
]

PRO_FEATURES = BUSINESS_FEATURES + [
    # HR — pro
    "hr.leave_management",
    "hr.attendance_tracking",
    "hr.shift_management",
    "hr.document_management",
    "hr.hr_analytics",
    # Projects — pro
    "projects.gantt_view",
    "projects.project_templates",
    # Time Tracking — billing
    "time_tracking.billable_tracking",
    # Helpdesk — pro
    "helpdesk.satisfaction_survey",
    "helpdesk.customer_portal",
    "helpdesk.multi_queue",
    # BPM — pro
    "bpm.process_control",
    "bpm.bpmn_diagrams",
    # AI — pro
    "ai.semantic_registry",
    "ai.action_dispatch",
    # Automation — pro
    "automation.action_templates",
    # IAM — pro
    "iam.mfa",
]

ENTERPRISE_FEATURES = PRO_FEATURES + [
    # HR — enterprise
    "hr.hr_analytics",
    "hr.sensitive_data",
    # Projects — enterprise
    "projects.gantt_view",
    "projects.project_templates",
    # Time Tracking — billing
    "time_tracking.billable_tracking",
    # Helpdesk — enterprise
    "helpdesk.satisfaction_survey",
    "helpdesk.ticket_merge",
    "helpdesk.advanced_reports",
    # BPM — enterprise
    "bpm.process_control",
    "bpm.bpmn_diagrams",
    # AI
    "ai.semantic_registry",
    "ai.action_dispatch",
    "ai.ai_assistant",
    # DMS — AI
    "dms.ai_tagging",
    "dms.workflow_integration",
    # Automation — advanced
    "automation.action_templates",
    # IAM — enterprise
    "iam.mfa",
    "iam.sso",
]

PLAN_ENTITLEMENTS: dict[str, list[str]] = {
    "free": FREE_FEATURES,
    "starter": STARTER_FEATURES,
    "business": BUSINESS_FEATURES,
    "pro": PRO_FEATURES,
    "enterprise": ENTERPRISE_FEATURES,
    "custom": ENTERPRISE_FEATURES,  # custom starts with all features
}


class Command(BaseCommand):
    help = "Seed default Plan records and their entitlement mappings."

    def add_arguments(self, parser):
        parser.add_argument(
            "--reset",
            action="store_true",
            help="Delete all existing PlanEntitlement rows before re-seeding.",
        )

    @transaction.atomic
    def handle(self, *args, **options):
        reset = options["reset"]
        created_plans = 0
        updated_plans = 0
        created_features = 0

        for plan_data in PLANS:
            code = plan_data["code"]
            features = PLAN_ENTITLEMENTS.get(code, [])

            plan, created = PlatformPlan.objects.update_or_create(
                code=code,
                defaults={k: v for k, v in plan_data.items() if k != "code"},
            )
            if created:
                created_plans += 1
            else:
                updated_plans += 1

            if reset:
                PlanFeature.objects.filter(plan=plan).delete()

            for fkey in features:
                _, feat_created = PlanFeature.objects.get_or_create(
                    plan=plan,
                    feature_key=fkey,
                    defaults={"enabled_by_default": True},
                )
                if feat_created:
                    created_features += 1

            self.stdout.write(
                self.style.SUCCESS(
                    f"  ✓ {code:12s}  {len(features):3d} entitlements"
                    f"  ({'created' if created else 'updated'})"
                )
            )

        self.stdout.write(
            self.style.SUCCESS(
                f"\nDone. Plans: {created_plans} created, {updated_plans} updated. "
                f"Features: {created_features} new rows."
            )
        )
