"""Seed RBAC menu permissions + default system roles.

Idempotent (get_or_create + set). Restored as a data migration after the
migration history was regenerated for the PostgreSQL move — the original
seed migrations (old 0010/0011/0013) were collapsed away by makemigrations,
which only captures schema, not RunPython data seeds.
"""

from django.db import migrations


DOMAINS = [
    ("project", "Project"),
    ("events", "Events"),
    ("hr", "HR"),
    ("finance", "Finance"),
    ("procurements", "Procurements"),
    ("asset_management", "Asset Management"),
    ("administrations", "Administrations"),
    ("publications", "Publications"),
    ("disseminations", "Disseminations"),
    ("phonebook", "Phonebook"),
    ("tasks", "Tasks"),
    ("analytics", "Analytics"),
]
BASE_ACTIONS = ["view", "create", "update", "delete"]
APPROVE_DOMAINS = {"project", "tasks", "finance", "procurements"}


ROLE_MATRIX = {
    "SuperAdmin": {
        "description": "Full access to every domain. Equivalent to is_superuser.",
        "patterns": ["*"],
    },
    "ProjectManager": {
        "description": "Manage projects + tasks. Read-only finance.",
        "patterns": ["project.*", "tasks.*", "finance.view"],
    },
    "HRManager": {
        "description": "Manage HR. Read phonebook.",
        "patterns": ["hr.*", "phonebook.view"],
    },
    "FinanceManager": {
        "description": "Manage finance. Approve procurement payments.",
        "patterns": ["finance.*", "procurements.view", "procurements.approve"],
    },
    "EventManager": {
        "description": "Manage events. Read phonebook.",
        "patterns": ["events.*", "phonebook.view"],
    },
    "Procurement": {
        "description": "Manage procurements. Read assets.",
        "patterns": ["procurements.*", "asset_management.view"],
    },
    "AssetManager": {
        "description": "Manage assets. Read procurements.",
        "patterns": ["asset_management.*", "procurements.view"],
    },
    "Publisher": {
        "description": "Manage publications.",
        "patterns": ["publications.*"],
    },
    "Communicator": {
        "description": "Manage disseminations. Read publications.",
        "patterns": ["disseminations.*", "publications.view"],
    },
    "Staff": {
        "description": "Default read-only baseline for new employees.",
        "patterns": [
            "project.view", "events.view", "tasks.view", "tasks.create",
            "phonebook.view",
        ],
    },
}


def _slugify(name):
    import re
    s = re.sub(r"(?<!^)(?=[A-Z])", "-", name)
    return s.lower().replace(" ", "-")


def _resolve_permissions(Permission, patterns):
    if patterns == ["*"]:
        return list(Permission.objects.all())
    ids = set()
    for p in patterns:
        domain, _, action = p.partition(".")
        if action == "*":
            ids.update(Permission.objects.filter(domain=domain).values_list("id", flat=True))
        else:
            ids.update(
                Permission.objects.filter(domain=domain, action=action).values_list("id", flat=True)
            )
    return list(Permission.objects.filter(id__in=ids))


def seed(apps, schema_editor):
    Permission = apps.get_model("core", "Permission")
    Role = apps.get_model("core", "Role")

    for slug, label in DOMAINS:
        for action in BASE_ACTIONS:
            Permission.objects.get_or_create(
                domain=slug, action=action,
                defaults={"label": f"{label}: {action.title()}"},
            )
        if slug in APPROVE_DOMAINS:
            Permission.objects.get_or_create(
                domain=slug, action="approve",
                defaults={"label": f"{label}: Approve"},
            )
    Permission.objects.get_or_create(
        domain="rbac", action="manage",
        defaults={"label": "RBAC: Manage roles and assignments"},
    )

    for name, cfg in ROLE_MATRIX.items():
        role, _ = Role.objects.get_or_create(
            slug=_slugify(name),
            defaults={"name": name, "description": cfg["description"], "is_system": True},
        )
        role.name = name
        role.description = cfg["description"]
        role.is_system = True
        role.save(update_fields=["name", "description", "is_system"])
        role.permissions.set(_resolve_permissions(Permission, cfg["patterns"]))


def unseed(apps, schema_editor):
    apps.get_model("core", "Role").objects.filter(is_system=True).delete()
    apps.get_model("core", "Permission").objects.all().delete()


class Migration(migrations.Migration):
    dependencies = [("core", "0001_initial")]
    operations = [migrations.RunPython(seed, unseed)]
