"""One-off seed: registers translation_keys English source_text and hi/mr/hinglish
translation_values for the "notifications" PageInfoButton content.

Usage: docker compose exec api python seed_translations_pageinfo_notifications.py
"""
import asyncio
import uuid
from datetime import datetime, timezone

from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from ams.core.config import settings

NAMESPACE = "help"

# key -> (english, hi, mr, hinglish)
NOTIFICATIONS = {
    "notifications.title": (
        "Notification Center",
        "नोटिफिकेशन सेंटर",
        "नोटिफिकेशन सेंटर",
        "Notification Center",
    ),
    "notifications.subtitle": (
        "Inbox, channel preferences, and safety-alert admin tools",
        "इनबॉक्स, चैनल प्राथमिकताएँ, और सेफ्टी-अलर्ट एडमिन टूल्स",
        "इनबॉक्स, चॅनेल प्राधान्ये, आणि सेफ्टी-अलर्ट अ‍ॅडमिन टूल्स",
        "Inbox, channel preferences, aur safety-alert admin tools",
    ),
    "notifications.body.0": (
        "Every notification the system sends you — custody reminders, workflow approvals, safety alerts — lands here. The Inbox tab lists them with an unread filter and an Acknowledge action; Preferences lets you opt in or out per delivery channel (DPDP Act 2023 consent); Admin (visible only with notification:admin permission) can broadcast critical safety alerts and manage suppression windows.",
        "सिस्टम द्वारा भेजा गया हर notification — custody reminders, workflow approvals, safety alerts — यहीं आता है। Inbox टैब में unread filter और Acknowledge action के साथ ये सूचीबद्ध होते हैं; Preferences में आप प्रत्येक delivery channel के लिए opt in या opt out कर सकते हैं (DPDP Act 2023 consent); Admin (केवल notification:admin permission के साथ दिखाई देता है) critical safety alerts broadcast कर सकता है और suppression windows manage कर सकता है।",
        "सिस्टमने पाठवलेली प्रत्येक notification — custody reminders, workflow approvals, safety alerts — इथेच येते. Inbox टॅबमध्ये unread filter आणि Acknowledge action सह त्या सूचीबद्ध होतात; Preferences मध्ये तुम्ही प्रत्येक delivery channel साठी opt in किंवा opt out करू शकता (DPDP Act 2023 consent); Admin (फक्त notification:admin permission सह दिसते) critical safety alerts broadcast करू शकतो आणि suppression windows manage करू शकतो.",
        "System jo bhi notification bhejta hai — custody reminders, workflow approvals, safety alerts — sab yahin aate hain. Inbox tab mein ye unread filter aur Acknowledge action ke saath list hote hain; Preferences mein aap har delivery channel ke liye opt in ya opt out kar sakte hain (DPDP Act 2023 consent); Admin (sirf notification:admin permission ke saath visible) critical safety alerts broadcast kar sakta hai aur suppression windows manage kar sakta hai.",
    ),
    "notifications.stepsHeading": (
        "Delivery lifecycle",
        "डिलीवरी लाइफ़साइकल",
        "डिलिव्हरी लाइफसायकल",
        "Delivery lifecycle",
    ),
    "notifications.steps.0.label": ("Queued", "कतार में", "रांगेत", "Queued"),
    "notifications.steps.0.caption": (
        "Event triggers the notification; it's queued for dispatch",
        "Event notification को ट्रिगर करता है; यह dispatch के लिए कतार में डाल दी जाती है।",
        "Event notification ट्रिगर करते; ती dispatch साठी रांगेत ठेवली जाते.",
        "Event notification ko trigger karta hai; ye dispatch ke liye queue mein chali jaati hai.",
    ),
    "notifications.steps.1.label": ("Sent", "भेजा गया", "पाठवले", "Sent"),
    "notifications.steps.1.caption": (
        "Dispatched on the recipient's opted-in channel(s)",
        "प्राप्तकर्ता के opted-in channel(s) पर dispatch की गई।",
        "प्राप्तकर्त्याच्या opted-in channel(s) वर dispatch केली.",
        "Recipient ke opted-in channel(s) par dispatch ho jaati hai.",
    ),
    "notifications.steps.2.label": ("Acknowledged", "स्वीकृत", "स्वीकृत", "Acknowledged"),
    "notifications.steps.2.caption": (
        "Recipient acknowledges it in the Inbox tab",
        "प्राप्तकर्ता इसे Inbox टैब में acknowledge करता है।",
        "प्राप्तकर्ता ते Inbox टॅबमध्ये acknowledge करतो.",
        "Recipient ise Inbox tab mein acknowledge karta hai.",
    ),
    "notifications.steps.3.label": ("Failed", "विफल", "अयशस्वी", "Failed"),
    "notifications.steps.3.caption": (
        "Alternate outcome — channel delivery errored out",
        "वैकल्पिक परिणाम — channel delivery में error आ गया।",
        "पर्यायी परिणाम — channel delivery मध्ये error आली.",
        "Alternate outcome — channel delivery mein error aa gaya.",
    ),
    "notifications.fieldRules.0.name": ("Channel", "चैनल", "चॅनेल", "Channel"),
    "notifications.fieldRules.0.description": (
        "Email, SMS, WhatsApp, or in-app — opt in/out per channel; defaults to opted in",
        "Email, SMS, WhatsApp, या in-app — प्रत्येक channel के लिए opt in/out करें; डिफ़ॉल्ट रूप से opted in रहता है।",
        "Email, SMS, WhatsApp, किंवा in-app — प्रत्येक channel साठी opt in/out करा; डीफॉल्टनुसार opted in असते.",
        "Email, SMS, WhatsApp, ya in-app — har channel ke liye opt in/out karein; default opted in rehta hai.",
    ),
    "notifications.fieldRules.1.name": ("Org Unit", "ऑर्ग यूनिट", "ऑर्ग युनिट", "Org Unit"),
    "notifications.fieldRules.1.description": (
        "Critical Safety Alert target — broadcasts to every custodian with active custody in that OU's subtree",
        "Critical Safety Alert का लक्ष्य — उस OU के subtree में active custody रखने वाले हर custodian को broadcast करता है।",
        "Critical Safety Alert चे लक्ष्य — त्या OU च्या subtree मध्ये active custody असलेल्या प्रत्येक custodian ला broadcast करते.",
        "Critical Safety Alert ka target — us OU ke subtree mein active custody rakhne wale har custodian ko broadcast karta hai.",
    ),
    "notifications.fieldRules.2.name": ("Alert Message", "अलर्ट मैसेज", "अलर्ट मेसेज", "Alert Message"),
    "notifications.fieldRules.2.description": (
        "Body of the critical safety alert; cannot be sent blank",
        "Critical safety alert का body; इसे खाली नहीं भेजा जा सकता।",
        "Critical safety alert चा body; तो रिकामा पाठवता येत नाही.",
        "Critical safety alert ka body; ise blank nahi bheja ja sakta.",
    ),
    "notifications.fieldRules.3.name": ("Rule Key", "रूल की", "रूल की", "Rule Key"),
    "notifications.fieldRules.3.description": (
        "Identifies which notification rule the suppression window silences",
        "यह पहचानता है कि suppression window किस notification rule को silent करती है।",
        "suppression window कोणत्या notification rule ला silent करते हे ओळखते.",
        "Ye identify karta hai ki suppression window kis notification rule ko silent karti hai.",
    ),
    "notifications.fieldRules.4.name": ("Suppressed Until", "सप्रेस्ड अंटिल", "सप्रेस्ड अंटिल", "Suppressed Until"),
    "notifications.fieldRules.4.description": (
        "Date/time the suppression window expires and the rule resumes firing",
        "वह date/time जब suppression window समाप्त होती है और rule फिर से fire होना शुरू करता है।",
        "ती date/time जेव्हा suppression window संपते आणि rule पुन्हा fire होऊ लागतो.",
        "Wo date/time jab suppression window expire hoti hai aur rule dubara fire hona shuru karta hai.",
    ),
    "notifications.tip.title": (
        "Critical alerts bypass suppression",
        "क्रिटिकल अलर्ट सप्रेशन को बायपास करते हैं",
        "क्रिटिकल अलर्ट सप्रेशनला बायपास करतात",
        "Critical alerts suppression ko bypass karte hain",
    ),
    "notifications.tip.body": (
        "Broadcast Alert on the Admin tab ignores both active suppression windows and per-user channel opt-outs — it always reaches every custodian in the OU subtree. Reserve it for genuine emergencies, since it can't be recalled once sent.",
        "Admin टैब पर Broadcast Alert, active suppression windows और per-user channel opt-outs दोनों को नज़रअंदाज़ करता है — यह हमेशा OU subtree के हर custodian तक पहुँचता है। इसे केवल वास्तविक आपात स्थितियों के लिए ही उपयोग करें, क्योंकि एक बार भेजने के बाद इसे वापस नहीं लिया जा सकता।",
        "Admin टॅबवरील Broadcast Alert, active suppression windows आणि per-user channel opt-outs या दोन्हींकडे दुर्लक्ष करते — ते नेहमी OU subtree मधील प्रत्येक custodian पर्यंत पोहोचते. फक्त खऱ्या आणीबाणीच्या परिस्थितीसाठीच याचा वापर करा, कारण एकदा पाठवल्यानंतर ते परत घेता येत नाही.",
        "Admin tab par Broadcast Alert, active suppression windows aur per-user channel opt-outs dono ko ignore karta hai — ye hamesha OU subtree ke har custodian tak pahunchta hai. Isse sirf genuine emergencies ke liye hi use karein, kyunki ek baar bhejne ke baad ise wapas nahi liya ja sakta.",
    ),
}


async def seed_for_session(session: AsyncSession) -> tuple[int, int]:
    now = datetime.now(timezone.utc)
    keys_upserted = 0
    values_upserted = 0
    for key, (en, hi, mr, hinglish) in NOTIFICATIONS.items():
        key_id = (await session.execute(
            text("SELECT id FROM translation_keys WHERE namespace = :ns AND key = :key"),
            {"ns": NAMESPACE, "key": key},
        )).scalar_one_or_none()
        if key_id:
            await session.execute(
                text("UPDATE translation_keys SET source_text = :src WHERE id = :id"),
                {"src": en, "id": key_id},
            )
        else:
            key_id = str(uuid.uuid4())
            await session.execute(
                text("""INSERT INTO translation_keys (id, namespace, key, source_text, created_at)
                        VALUES (:id, :ns, :key, :src, :now)"""),
                {"id": key_id, "ns": NAMESPACE, "key": key, "src": en, "now": now},
            )
            keys_upserted += 1

        for lang_code, value in (("hi", hi), ("mr", mr), ("hinglish", hinglish)):
            existing = (await session.execute(
                text("SELECT id FROM translation_values WHERE key_id = :kid AND language_code = :lc"),
                {"kid": key_id, "lc": lang_code},
            )).scalar_one_or_none()
            if existing:
                await session.execute(
                    text("UPDATE translation_values SET value = :val, updated_at = :now WHERE id = :id"),
                    {"val": value, "now": now, "id": existing},
                )
            else:
                await session.execute(
                    text("""INSERT INTO translation_values (id, key_id, language_code, value, updated_by, updated_at)
                            VALUES (:id, :kid, :lc, :val, NULL, :now)"""),
                    {"id": str(uuid.uuid4()), "kid": key_id, "lc": lang_code, "val": value, "now": now},
                )
                values_upserted += 1
    await session.commit()
    return keys_upserted, values_upserted


async def main() -> None:
    engine = create_async_engine(settings.DATABASE_URL, echo=False)
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with Session() as session:
        tenants = (await session.execute(
            text("SELECT id::text AS id, slug FROM public.tenants WHERE status != 'archived'")
        )).fetchall()

    for tenant in tenants:
        schema = f"tenant_{tenant.id.replace('-', '_')}"
        async with Session() as session:
            await session.execute(text(f"SET search_path TO {schema}, public"))
            try:
                k, v = await seed_for_session(session)
                print(f"  seeded {k} new keys, {v} new values: {tenant.slug}")
            except Exception as exc:
                print(f"  SKIPPED {tenant.slug}: {exc}")
                await session.rollback()

    await engine.dispose()
    print(f"Done — {len(tenants)} tenant(s) processed, {len(NOTIFICATIONS)} notifications keys.")


if __name__ == "__main__":
    asyncio.run(main())
