"""Seed the Voice Agents sidebar menus and grant access to manager roles.

Run after migrating:  python master_seeder/add_voice_agents_menu.py

Structure:
    Voice Agents (parent, sort_order 9)
    ├── Manage Agents   /voice-agents   ai_calls.view_voiceagent
    └── Create Agent    /voice-agents   ai_calls.add_voiceagent

sort_order 9 is deliberate: existing top-level items occupy 1-8 (Dashboard …
Master Data) and 16 (Password Policy), so slot 9 is free and NO existing menu
item moves. The parent carries a blank permission_code and appears only when a
child is visible — the existing Menu contract.

Permissions go to every group whose name contains MANAGER, mirroring
add_reports_menu.py. ADMIN sees every menu automatically. Recruiters and other
roles receive nothing here, so the module stays invisible to them.

Idempotent — safe to re-run.
"""

import django
import os
import sys

VIEW_PERM = "ai_calls.view_voiceagent"
ADD_PERM = "ai_calls.add_voiceagent"
CHANGE_PERM = "ai_calls.change_voiceagent"
ROUTE = "/voice-agents"
PARENT_SORT_ORDER = 9


def add_voice_agents_menus():
    from django.contrib.auth.models import Group, Permission

    from apps.menus.models import Menu

    # --- guard: the permissions must exist before we point menus at them ---
    perms = {}
    for code in (VIEW_PERM, ADD_PERM, CHANGE_PERM):
        app_label, codename = code.split(".", 1)
        perm = Permission.objects.filter(
            content_type__app_label=app_label, codename=codename
        ).first()
        if not perm:
            print(f"ERROR: {code} not found — run `python manage.py migrate` first.")
            sys.exit(1)
        perms[code] = perm

    # --- guard: never silently steal an occupied top-level slot ---
    clash = (
        Menu.objects.filter(parent__isnull=True, sort_order=PARENT_SORT_ORDER)
        .exclude(name="Voice Agents")
        .first()
    )
    if clash:
        print(
            f"ERROR: top-level sort_order {PARENT_SORT_ORDER} is taken by '{clash.name}'. "
            "Pick a free slot rather than reordering existing menus."
        )
        sys.exit(1)

    parent, created = Menu.objects.get_or_create(
        name="Voice Agents",
        parent=None,
        defaults={
            "route": "",
            "icon": "fa-solid fa-microphone-lines",
            "sort_order": PARENT_SORT_ORDER,
            "permission_code": "",
            "is_active": True,
            "admin_only": False,
        },
    )
    if not created:
        parent.route = ""
        parent.icon = "fa-solid fa-microphone-lines"
        parent.sort_order = PARENT_SORT_ORDER
        parent.permission_code = ""
        parent.is_active = True
        parent.admin_only = False
        parent.save()
    print(f"{'Created' if created else 'Updated'} parent menu 'Voice Agents' (sort_order {PARENT_SORT_ORDER}).")

    children = [
        ("Manage Agents", 1, "fa-solid fa-list", VIEW_PERM),
        ("Create Agent", 2, "fa-solid fa-plus", ADD_PERM),
    ]
    for name, order, icon, perm_code in children:
        child, made = Menu.objects.get_or_create(
            name=name,
            parent=parent,
            defaults={
                "route": ROUTE,
                "icon": icon,
                "sort_order": order,
                "permission_code": perm_code,
                "is_active": True,
                "admin_only": False,
            },
        )
        if not made:
            child.route = ROUTE
            child.icon = icon
            child.sort_order = order
            child.permission_code = perm_code
            child.is_active = True
            child.save()
        print(f"  {'Created' if made else 'Updated'} child '{name}' ({ROUTE}) -> {perm_code}")

    manager_groups = Group.objects.filter(name__icontains="MANAGER")
    if not manager_groups.exists():
        print("No *MANAGER* groups found — nothing to grant (admins still see Voice Agents).")
    for group in manager_groups:
        group.permissions.add(perms[VIEW_PERM], perms[ADD_PERM], perms[CHANGE_PERM])
        print(f"Granted view/add/change_voiceagent to group '{group.name}'.")


if __name__ == "__main__":
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
    django.setup()
    add_voice_agents_menus()
