"""Phase C — 3-Level Feature Key Migration (sections 2.4 + 5.3).

Converts all 2-level feature keys (``module.feature_name``) to canonical
3-level format (``module.capability.feature``) across all database tables.

=== Tables Updated ===
  - modules_featurecatalog.code
  - modules_featureentitlement.feature_key
  - modules_featureentitlement.capability_key
  - modules_tenantfeatureoverride.feature_key
  - subscription_planfeature.feature_key
  - subscription_tenantaddonfeature.feature_key

=== Rollback ===
  Reverse migration restores old 2-level keys using the reverse mapping.
"""

from django.db import migrations


# ── Feature key mapping: OLD (2-level) → NEW (3-level) ────────────────────
FEATURE_KEY_MAP: dict[str, str] = {
    # ── Workbox ────────────────────────────────────────────────────────
    "workbox.workitem_my_work": "workbox.work.workitem_my_work",
    "workbox.workitem_pending_approvals": "workbox.work.workitem_pending_approvals",
    "workbox.workitem_delegated": "workbox.work.workitem_delegated",
    "workbox.workitem_overdue": "workbox.work.workitem_overdue",
    "workbox.workitem_completed": "workbox.work.workitem_completed",
    "workbox.workitem_dashboard": "workbox.work.workitem_dashboard",
    "workbox.workitem_unified_search": "workbox.work.workitem_unified_search",
    "workbox.workitem_realtime": "workbox.work.workitem_realtime",
    "workbox.workitem_create": "workbox.work.workitem_create",
    "workbox.workitem_timeline": "workbox.work.workitem_timeline",
    # ── Visualization ───────────────────────────────────────────────────
    "visualization.view_configurations": "visualization.views.view_configurations",
    "visualization.dashboard_engine": "visualization.views.dashboard_engine",
    "visualization.chart_engine": "visualization.views.chart_engine",
    "visualization.saved_views": "visualization.views.saved_views",
    "visualization.view_export": "visualization.views.view_export",
    # ── Time Tracking ───────────────────────────────────────────────────
    "time_tracking.time_logging": "time_tracking.tracking.time_logging",
    "time_tracking.time_approval": "time_tracking.tracking.time_approval",
    "time_tracking.time_reports": "time_tracking.tracking.time_reports",
    "time_tracking.billable_tracking": "time_tracking.tracking.billable_tracking",
    # ── Notifications ───────────────────────────────────────────────────
    "notifications.in_app_notifications": "notifications.delivery.in_app_notifications",
    "notifications.email_notifications": "notifications.delivery.email_notifications",
    "notifications.sms_notifications": "notifications.delivery.sms_notifications",
    "notifications.notification_preferences": "notifications.delivery.notification_preferences",
    # ── Reporting ───────────────────────────────────────────────────────
    "reporting.report_viewer": "reporting.reports.report_viewer",
    "reporting.report_filters": "reporting.reports.report_filters",
    "reporting.report_exports": "reporting.reports.report_exports",
    "reporting.scheduled_reports": "reporting.reports.scheduled_reports",
    "reporting.kpi_dashboards": "reporting.dashboards.kpi_dashboards",
    # ── Platform Core ───────────────────────────────────────────────────
    "platform_core.base_models": "platform_core.core.base_models",
    "platform_core.scoped_queries": "platform_core.core.scoped_queries",
    "platform_core.global_search": "platform_core.search.global_search",
    "platform_core.attachments": "platform_core.files.attachments",
    "platform_core.comments": "platform_core.collaboration.comments",
    "platform_core.activity_feed": "platform_core.collaboration.activity_feed",
    "platform_core.custom_fields": "platform_core.forms.custom_fields",
    "platform_core.tags": "platform_core.collaboration.tags",
    "platform_core.notes": "platform_core.collaboration.notes",
    "platform_core.dynamic_forms": "platform_core.forms.dynamic_forms",
    "platform_core.reference_numbers": "platform_core.core.reference_numbers",
    "platform_core.import_engine": "platform_core.io.import_engine",
    "platform_core.export_engine": "platform_core.io.export_engine",
    "platform_core.print_engine": "platform_core.print.print_engine",
    "platform_core.message_templates": "platform_core.templates.message_templates",
    "platform_core.document_templates": "platform_core.templates.document_templates",
    "platform_core.export_layouts": "platform_core.io.export_layouts",
    # ── Escalation Engine ───────────────────────────────────────────────
    "escalation_engine.escalation_rule_management": "escalation_engine.management.escalation_rule_management",
    "escalation_engine.escalation_instance_tracking": "escalation_engine.management.escalation_instance_tracking",
    "escalation_engine.escalation_hierarchy": "escalation_engine.management.escalation_hierarchy",
    "escalation_engine.escalation_time_based": "escalation_engine.management.escalation_time_based",
    # ── Storage ─────────────────────────────────────────────────────────
    "storage.file_processing": "storage.files.file_processing",
    # ── Provisioning ────────────────────────────────────────────────────
    "provisioning.seed_runner": "provisioning.fixtures.seed_runner",
    "provisioning.snapshot_manager": "provisioning.fixtures.snapshot_manager",
    "provisioning.benchmark_generator": "provisioning.fixtures.benchmark_generator",
    # ── BPM ─────────────────────────────────────────────────────────────
    "bpm.pcf_framework": "bpm.processes.pcf_framework",
    "bpm.process_definition": "bpm.processes.process_definition",
    "bpm.raci_matrix": "bpm.processes.raci_matrix",
    "bpm.kpi_management": "bpm.processes.kpi_management",
    "bpm.process_execution": "bpm.processes.process_execution",
    "bpm.process_control": "bpm.processes.process_control",
    "bpm.bpmn_diagrams": "bpm.processes.bpmn_diagrams",
    # ── Projects (mixed — some were already 3-level) ────────────────────
    "projects.project_phases": "projects.management.project_phases",
    "projects.milestones": "projects.management.milestones",
    "projects.team_management": "projects.collaboration.team_management",
    "projects.gantt_view": "projects.management.gantt_view",
    "projects.project_templates": "projects.management.project_templates",
    # ── SLA Engine (mixed — some were already 3-level) ──────────────────
    "sla_engine.sla_breach_monitoring": "sla_engine.policies.sla_breach_monitoring",
    "sla_engine.sla_recovery": "sla_engine.policies.sla_recovery",
    # ── Tasks (mixed — some were already 3-level) ───────────────────────
    "tasks.subtasks": "tasks.management.subtasks",
    "tasks.task_comments": "tasks.management.task_comments",
    "tasks.task_attachments": "tasks.management.task_attachments",
    "tasks.task_watchers": "tasks.management.task_watchers",
    "tasks.task_templates": "tasks.management.task_templates",
}

# Reverse map for rollback
REVERSE_MAP: dict[str, str] = {v: k for k, v in FEATURE_KEY_MAP.items()}

# ── Tables and their feature-key columns ──────────────────────────────────
MODELS_WITH_FEATURE_KEY: list[tuple[str, str, str]] = [
    # (app_label, model_name, field_name)
    ("platform_modules", "FeatureCatalog", "code"),
    ("platform_modules", "FeatureEntitlement", "feature_key"),
    ("subscription", "PlanFeature", "feature_key"),
    ("platform_modules", "TenantFeatureOverride", "feature_key"),
    ("subscription", "TenantAddonFeature", "feature_key"),
]


def migrate_feature_keys(apps, schema_editor, mapping: dict[str, str]):
    """Apply feature key mapping to all relevant tables."""
    for app_label, model_name, field in MODELS_WITH_FEATURE_KEY:
        Model = apps.get_model(app_label, model_name)
        qs = Model.objects.all()
        updated = 0
        for obj in qs.iterator(chunk_size=500):
            old_key = getattr(obj, field)
            if not old_key:
                continue
            new_key = mapping.get(old_key)
            if new_key and new_key != old_key:
                setattr(obj, field, new_key)
                obj.save(update_fields=[field])
                updated += 1
        if updated:
            print(f"  {app_label}.{model_name}.{field}: {updated} keys migrated")


def forward_migration(apps, schema_editor):
    """Migrate 2-level feature keys → 3-level."""
    migrate_feature_keys(apps, schema_editor, FEATURE_KEY_MAP)


def reverse_migration(apps, schema_editor):
    """Rollback 3-level feature keys → 2-level."""
    migrate_feature_keys(apps, schema_editor, REVERSE_MAP)


class Migration(migrations.Migration):
    """Phase C — Convert feature keys from 2-level to 3-level naming.

    Run AFTER Phase A (Domain+Capability) and Phase B (Plan/Addon/Entitlement).
    Must be the last migration in the chain so all tables have their final schema.
    """

    dependencies = [
        ("platform_modules", "0017_phase_b_decouple_tier"),
        ("subscription", "__latest__"),
    ]

    operations = [
        migrations.RunPython(
            forward_migration,
            reverse_migration,
        ),
    ]
