import json
from django.core.management.base import BaseCommand
from pxy_dashboard.models import SidebarMenuItem

class Command(BaseCommand):
    help = "Carga el menú lateral desde un archivo JSON"

    def add_arguments(self, parser):
        parser.add_argument("json_file", type=str, help="Ruta al archivo JSON")

    def handle(self, *args, **kwargs):
        json_path = kwargs["json_file"]
        with open(json_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        created = self.create_menu_items(data)
        self.stdout.write(self.style.SUCCESS(f"{created} ítems de menú creados."))

    def create_menu_items(self, items, parent=None):
        count = 0
        for item in items:
            children = item.pop("children", [])
            menu_item = SidebarMenuItem.objects.create(parent=parent, **item)
            count += 1
            if children:
                count += self.create_menu_items(children, parent=menu_item)
        return count
