"""Add a 'Notification Templates' item under the Master Data sidebar group,
and seed one default email template. Idempotent.

Run:  python add_notification_templates_menu.py
"""
import django, os, sys


def run():
    from apps.menus.models import Menu
    from apps.notifications.models import NotificationTemplate

    parent = Menu.objects.filter(name="Master Data", parent__isnull=True).first()
    if not parent:
        print("ERROR: 'Master Data' parent not found — run master-data seeders first.")
        sys.exit(1)
    last = parent.children.order_by("-sort_order").first()
    item, created = Menu.objects.get_or_create(
        name="Notification Templates", parent=parent,
        defaults={
            "route": "/master-data/notification-templates", "icon": "fa-solid fa-bell",
            "sort_order": (last.sort_order + 1) if last else 1,
            "permission_code": "", "is_active": True, "admin_only": True,
        },
    )
    if not created:
        item.route = "/master-data/notification-templates"; item.icon = "fa-solid fa-bell"
        item.is_active = True; item.admin_only = True; item.save()
    print(f"{'Created' if created else 'Updated'} 'Notification Templates' menu under Master Data.")

    # Default template per channel (only if that channel has none yet).
    defaults = [
        {
            "channel": "EMAIL",
            "name": "Job opportunity (default)",
            "subject": "A job that matches your profile — {{job_title}}",
            "body": ("Hi {{first_name}},\n\nWe have an opening for {{job_title}} at {{company}} "
                     "({{location}}) that fits your profile. Reply or apply if you're interested.\n\n"
                     "Regards,\nIndovision Talent Team"),
            "provider_template_name": "",
        },
        {
            "channel": "WHATSAPP",
            "name": "Job alert (default)",
            "subject": "",
            "body": ("Hi {{first_name}}, we have a {{job_title}} opening at {{company}} "
                     "({{location}}). Interested? Reply YES to know more. - Indovision"),
            # Set this to the approved WhatsApp template name on the gateway (send2.digital).
            "provider_template_name": "job_alert",
        },
        {
            "channel": "SMS",
            "name": "Job alert SMS (default)",
            "subject": "",
            "body": ("Hi {{first_name}}, a {{job_title}} role at {{company}} matches your profile. "
                     "Reply to know more. - Indovision"),
            # Set this to the approved DLT/SMS template/content id.
            "provider_template_name": "",
        },
    ]
    for d in defaults:
        if not NotificationTemplate.objects.filter(channel=d["channel"], purpose="GENERAL").exists():
            NotificationTemplate.objects.create(is_active=True, purpose="GENERAL", **d)
            print(f"Seeded default {d['channel']} template.")
        else:
            print(f"{d['channel']} GENERAL template already exists — skipped.")

    # OTP templates (verification code). Text + provider ref (WhatsApp template
    # name / SMS DLT content-id) are managed from the master — set the real
    # approved values there. {{otp}} is substituted at send time.
    otp_defaults = [
        {
            "channel": "SMS",
            "name": "Login OTP (SMS)",
            "subject": "",
            "body": "{{otp}} is your OTP for login in iHRMS portal - Indovision Services Pvt. Ltd",
            # SMS: DLT content-id. Replace with the OTP template's approved content-id.
            "provider_template_name": "",
        },
        {
            "channel": "WHATSAPP",
            "name": "Login OTP (WhatsApp)",
            "subject": "",
            "body": "{{otp}}",
            # WhatsApp: approved template name for OTP (e.g. otp_1).
            "provider_template_name": "otp_1",
        },
    ]
    for d in otp_defaults:
        if not NotificationTemplate.objects.filter(channel=d["channel"], purpose="OTP").exists():
            NotificationTemplate.objects.create(is_active=True, purpose="OTP", **d)
            print(f"Seeded OTP {d['channel']} template.")
        else:
            print(f"{d['channel']} OTP template already exists — skipped.")


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