# seed_rbac_permissions.py

import os
import sys
import inspect

import django


# ============================================================
# Django setup
# ============================================================

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

sys.path.insert(0, BASE_DIR)

os.environ.setdefault(
    "DJANGO_SETTINGS_MODULE",
    "indizene.settings"
)

django.setup()


# ============================================================
# Imports after Django setup
# ============================================================

from admin_panel.models import Permission
from admin_panel import views


# ============================================================
# HTTP Method → RBAC Action
# ============================================================

METHOD_TO_ACTION = {
    "get": "view",
    "post": "add",
    "patch": "edit",
    "put": "edit",
    "delete": "delete",
}


# ============================================================
# Find module permissions from views.py
# ============================================================

module_actions = {}


for class_name, cls in inspect.getmembers(
    views,
    inspect.isclass
):

    # Ignore imported classes
    if cls.__module__ != views.__name__:
        continue

    # Get module_name
    module_name = getattr(
        cls,
        "module_name",
        None
    )

    if not module_name:
        continue

    # Create module entry
    actions = module_actions.setdefault(
        module_name,
        set()
    )

    # Check actual methods defined inside this class
    for method_name, action in METHOD_TO_ACTION.items():

        if method_name in cls.__dict__:
            actions.add(action)


# ============================================================
# Display what will be created
# ============================================================

print("\n==============================================")
print("RBAC PERMISSION REBUILD")
print("==============================================")

print(
    f"\nModules detected: {len(module_actions)}\n"
)

for module_name, actions in sorted(
    module_actions.items()
):

    print(
        f"{module_name}: "
        f"{', '.join(sorted(actions))}"
    )


# ============================================================
# Delete old permissions
# ============================================================

print("\n----------------------------------------------")
print("Deleting old permissions...")
print("----------------------------------------------")

old_count = Permission.objects.count()

Permission.objects.all().delete()

print(
    f"Deleted {old_count} old permissions."
)


# ============================================================
# Create new permissions
# ============================================================

print("\n----------------------------------------------")
print("Creating new permissions...")
print("----------------------------------------------")

created_count = 0


for module_name, actions in sorted(
    module_actions.items()
):

    for action in sorted(actions):

        Permission.objects.create(
            module=module_name,
            action=action
        )

        created_count += 1

        print(
            f"Created: "
            f"{module_name} → {action}"
        )


# ============================================================
# Final summary
# ============================================================

print("\n==============================================")
print("RBAC PERMISSION REBUILD COMPLETED")
print("==============================================")

print(
    f"Modules     : {len(module_actions)}"
)

print(
    f"Permissions : {created_count}"
)

print(
    f"Database    : {Permission.objects.count()}"
)

print("==============================================\n")