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

Usage: docker compose exec api python seed_translations_pageinfo_alert_masters.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)
ALERT_MASTERS = {
    "alert-masters.title": (
        "Alert Masters",
        "अलर्ट मास्टर",
        "अलर्ट मास्टर",
        "Alert Masters",
    ),
    "alert-masters.subtitle": (
        "Reusable alert templates you can dispatch on demand",
        "पुनः प्रयोग योग्य अलर्ट टेम्पलेट्स जिन्हें आप मांग पर भेज सकते हैं",
        "पुनर्वापर करण्यायोग्य अलर्ट टेम्पलेट्स जे तुम्ही मागणीनुसार पाठवू शकता",
        "Reusable alert templates jinhe aap on-demand dispatch kar sakte hain",
    ),
    "alert-masters.body.0": (
        "Author alert content (header/description/footer) and pick which channel(s) — email, SMS, WhatsApp — it sends through. Use Send to dispatch it to chosen recipients right away.",
        "Alert content (header/description/footer) तैयार करें और चुनें कि वह किस channel(s) — email, SMS, WhatsApp — के ज़रिए भेजा जाए। चुने गए recipients को तुरंत भेजने के लिए Send का उपयोग करें।",
        "Alert content (header/description/footer) तयार करा आणि तो कोणत्या channel(s) — email, SMS, WhatsApp — मार्फत पाठवायचा ते निवडा. निवडलेल्या recipients ना लगेच पाठवण्यासाठी Send वापरा.",
        "Alert content (header/description/footer) author karein aur choose karein ki wo kaunse channel(s) — email, SMS, WhatsApp — ke through jaayega. Chuni gayi recipients ko turant dispatch karne ke liye Send use karein.",
    ),
    "alert-masters.stepsHeading": (
        "Alert lifecycle",
        "अलर्ट लाइफ़साइकल",
        "अलर्ट लाइफसायकल",
        "Alert lifecycle",
    ),
    "alert-masters.steps.0.label": ("Draft", "ड्राफ़्ट", "ड्राफ्ट", "Draft"),
    "alert-masters.steps.0.caption": (
        "Saved on create, pending approval",
        "बनाते समय सेव किया गया, अनुमोदन लंबित",
        "तयार करताना सेव्ह केले, मंजुरी प्रलंबित",
        "Create karte hi save hota hai, approval pending rehta hai",
    ),
    "alert-masters.steps.1.label": ("Active", "सक्रिय", "सक्रिय", "Active"),
    "alert-masters.steps.1.caption": (
        "Approved — now sendable and editable",
        "अनुमोदित — अब भेजने और संपादित करने योग्य",
        "मंजूर — आता पाठवण्यायोग्य आणि संपादनयोग्य",
        "Approved ho chuka hai — ab sendable aur editable hai",
    ),
    "alert-masters.steps.2.label": ("Send", "भेजें", "पाठवा", "Send"),
    "alert-masters.steps.2.caption": (
        "Pick recipients, dispatch via chosen channel(s)",
        "Recipients चुनें, चुने गए channel(s) के ज़रिए भेजें",
        "Recipients निवडा, निवडलेल्या channel(s) मार्फत पाठवा",
        "Recipients pick karein, chune gaye channel(s) ke through dispatch karein",
    ),
    "alert-masters.steps.3.label": ("Archived", "आर्काइव्ड", "आर्काइव्ह्ड", "Archived"),
    "alert-masters.steps.3.caption": (
        "Deactivated — hidden from Send, kept for history",
        "निष्क्रिय किया गया — Send से छिपा हुआ, इतिहास के लिए रखा गया",
        "निष्क्रिय केले — Send मधून लपवले, इतिहासासाठी ठेवले",
        "Deactivate ho jaata hai — Send se hide rehta hai, history ke liye rakha jaata hai",
    ),
    "alert-masters.fieldRules.0.name": ("Code", "कोड", "कोड", "Code"),
    "alert-masters.fieldRules.0.description": (
        "Unique identifier; locked once saved, cannot be edited later.",
        "यूनीक पहचानकर्ता; एक बार सेव होने पर लॉक हो जाता है, बाद में संपादित नहीं किया जा सकता।",
        "युनिक ओळखकर्ता; एकदा सेव्ह झाल्यावर लॉक होते, नंतर संपादित करता येत नाही.",
        "Unique identifier hai; ek baar save hone ke baad lock ho jaata hai, baad mein edit nahi kiya ja sakta.",
    ),
    "alert-masters.fieldRules.1.name": ("Name", "नाम", "नाव", "Name"),
    "alert-masters.fieldRules.1.description": (
        "Display label shown in the list and on the Send dialog title.",
        "list में और Send dialog के title पर दिखाया जाने वाला display label।",
        "list मध्ये आणि Send dialog च्या title वर दाखवला जाणारा display label.",
        "List mein aur Send dialog ke title par dikhne wala display label.",
    ),
    "alert-masters.fieldRules.2.name": ("Send Via", "भेजने का माध्यम", "पाठवण्याचे माध्यम", "Send Via"),
    "alert-masters.fieldRules.2.description": (
        "At least one of Email / SMS / WhatsApp must be checked.",
        "Email / SMS / WhatsApp में से कम से कम एक को चेक करना ज़रूरी है।",
        "Email / SMS / WhatsApp पैकी किमान एक चेक करणे आवश्यक आहे.",
        "Email / SMS / WhatsApp mein se kam se kam ek check karna zaroori hai.",
    ),
    "alert-masters.fieldRules.3.name": ("Header / Footer", "हेडर / फ़ुटर", "हेडर / फूटर", "Header / Footer"),
    "alert-masters.fieldRules.3.description": (
        "Rich-text HTML wrapped around the description when the alert is sent.",
        "Alert भेजे जाने पर description के चारों ओर लपेटा गया rich-text HTML।",
        "Alert पाठवताना description भोवती गुंडाळलेले rich-text HTML.",
        "Alert send hote waqt description ke around wrap hone wala rich-text HTML.",
    ),
    "alert-masters.tip.title": (
        "Send only appears when Active",
        "Send केवल तब दिखता है जब Active हो",
        "Send फक्त Active असतानाच दिसते",
        "Send tabhi dikhta hai jab status Active ho",
    ),
    "alert-masters.tip.body": (
        "The Send button is hidden for Draft (pending-approval) and Archived alerts — only alerts that are both is_active and status=Active can be dispatched to recipients.",
        "Draft (अनुमोदन-लंबित) और Archived alerts के लिए Send button छिपा रहता है — केवल वे alerts जो is_active और status=Active दोनों हैं, recipients को भेजे जा सकते हैं।",
        "Draft (मंजुरी-प्रलंबित) आणि Archived alerts साठी Send button लपवलेले असते — फक्त ज्या alerts is_active आणि status=Active दोन्ही आहेत त्याच recipients ना पाठवता येतात.",
        "Draft (approval-pending) aur Archived alerts ke liye Send button hidden rehta hai — sirf wo alerts jo is_active aur status=Active dono hain, recipients ko dispatch kiye ja sakte hain.",
    ),
}


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 ALERT_MASTERS.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(ALERT_MASTERS)} alert-masters keys.")


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