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

Run after migrating:  python add_reports_menu.py

Structure:
    Reports (parent)
    ├── Reports Dashboard       /reports
    └── Overall ATS Dashboard   /reports/overall-dashboard

Both children are gated by reports.view_reports; the parent shows whenever a
child is visible. The permission is granted to every group whose name contains
MANAGER (TA_MANAGER, PROJECT_MANAGER, HIRING_MANAGER, ...). ADMIN sees all
menus automatically; recruiters and other roles never receive the permission.
Idempotent — re-running upgrades the old flat "Reports" item into the tree.
"""

import django
import os
import sys

PERM_CODE = "reports.view_reports"


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

    from apps.menus.models import Menu

    # Parent node (route empty — it only toggles the submenu)
    parent = Menu.objects.filter(name="Reports", parent__isnull=True).exclude(route="/reports").first()
    if not parent:
        parent = Menu.objects.create(
            name="Reports", route="", icon="fa-solid fa-chart-line",
            sort_order=7, permission_code="", is_active=True, admin_only=False,
        )
        print("Created parent menu 'Reports'.")

    # Child 1: the original /reports item (converted if it predates the tree)
    dash = Menu.objects.filter(route="/reports").first()
    if dash:
        dash.name = "Reports Dashboard"
        dash.parent = parent
        dash.icon = "fa-solid fa-chart-pie"
        dash.sort_order = 1
        dash.permission_code = PERM_CODE
        dash.is_active = True
        dash.save()
        print("Updated child 'Reports Dashboard' (/reports).")
    else:
        Menu.objects.create(
            name="Reports Dashboard", route="/reports", parent=parent,
            icon="fa-solid fa-chart-pie", sort_order=1,
            permission_code=PERM_CODE, is_active=True, admin_only=False,
        )
        print("Created child 'Reports Dashboard' (/reports).")

    # Child 2: Overall ATS Dashboard
    overall, created = Menu.objects.get_or_create(
        route="/reports/overall-dashboard",
        defaults={
            "name": "Overall ATS Dashboard",
            "parent": parent,
            "icon": "fa-solid fa-gauge-high",
            "sort_order": 2,
            "permission_code": PERM_CODE,
            "is_active": True,
            "admin_only": False,
        },
    )
    if not created:
        overall.name = "Overall ATS Dashboard"
        overall.parent = parent
        overall.permission_code = PERM_CODE
        overall.is_active = True
        overall.save()
    print(f"{'Created' if created else 'Updated'} child 'Overall ATS Dashboard' (/reports/overall-dashboard).")

    # Child 3: Candidate Reports — visible to recruiters too, so it carries the
    # auto view permission of the CandidateReport model instead of view_reports.
    CAND_PERM_CODE = "reports.view_candidatereport"
    cand_reports, created = Menu.objects.get_or_create(
        route="/reports/candidate-reports",
        defaults={
            "name": "Candidate Reports",
            "parent": parent,
            "icon": "fa-solid fa-file-pdf",
            "sort_order": 3,
            "permission_code": CAND_PERM_CODE,
            "is_active": True,
            "admin_only": False,
        },
    )
    if not created:
        cand_reports.name = "Candidate Reports"
        cand_reports.parent = parent
        cand_reports.permission_code = CAND_PERM_CODE
        cand_reports.is_active = True
        cand_reports.save()
    print(f"{'Created' if created else 'Updated'} child 'Candidate Reports' (/reports/candidate-reports).")

    try:
        perm = Permission.objects.get(content_type__app_label="reports", codename="view_reports")
    except Permission.DoesNotExist:
        print("ERROR: reports.view_reports permission not found — run `python manage.py migrate` first.")
        sys.exit(1)
    try:
        cand_perm = Permission.objects.get(content_type__app_label="reports", codename="view_candidatereport")
    except Permission.DoesNotExist:
        print("ERROR: reports.view_candidatereport not found — run `python manage.py migrate` first.")
        sys.exit(1)

    manager_groups = Group.objects.filter(name__icontains="MANAGER")
    if not manager_groups.exists():
        print("No *MANAGER* groups found — nothing to grant (admins still see Reports).")
    for group in manager_groups:
        group.permissions.add(perm, cand_perm)
        print(f"Granted {PERM_CODE} + {CAND_PERM_CODE} to group '{group.name}'.")

    recruiter_group = Group.objects.filter(name="RECRUITER").first()
    if recruiter_group:
        recruiter_group.permissions.add(cand_perm)
        print(f"Granted {CAND_PERM_CODE} to group 'RECRUITER'.")


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_reports_menus()
