# Generated by Django 5.2.8 on 2025-11-24 18:01

from django.db import migrations, models
from django.db.models import Q


def set_module_priorities(apps, schema_editor):
    Module = apps.get_model("pages", "Module")
    NodeRole = apps.get_model("nodes", "NodeRole")

    priority_rules = (
        (Q(menu__iexact="Cookbooks"), 1),
        (Q(menu__iexact="Charge Points") | Q(menu__iexact="Chargers"), 2),
        (Q(menu__iexact="Calculators") | Q(application__name__iexact="awg"), 3),
        (
            Q(menu__iexact="Constellation")
            | Q(application__name__iexact="constellation")
            | Q(path__iexact="/constellation/")
            | Q(path__iexact="/constellation"),
            4,
        ),
    )

    for condition, priority in priority_rules:
        Module.objects.filter(condition).update(priority=priority)

    watchtower = NodeRole.objects.filter(name="Watchtower").first()
    if watchtower:
        Module.objects.filter(node_role=watchtower, path="/read/").update(priority=1)
        Module.objects.filter(node_role=watchtower, path="/ocpp/").update(priority=2)
        Module.objects.filter(node_role=watchtower, path="/awg/").update(priority=3)


class Migration(migrations.Migration):

    dependencies = [
        ("pages", "0042_seed_dashboard_rules"),
    ]

    operations = [
        migrations.AddField(
            model_name="module",
            name="priority",
            field=models.PositiveIntegerField(
                default=0, help_text="Lower values appear first in navigation pills."
            ),
        ),
        migrations.RunPython(set_module_priorities, migrations.RunPython.noop),
    ]
