"""One-off seed: registers translation_keys English source_text and hi/mr/hinglish
translation_values for the 79 Master Data admin UI strings (Alert Masters, Template
Masters, Dynamic Fields, System Configuration notification channels) that were
already wrapped in t(key, englishFallback) calls but never seeded — so hi/mr/hinglish
users were seeing raw English fallback text.

Usage: docker compose exec api python seed_translations_gap_batch2_masterdata.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 = "app"

# key -> (english, hi, mr, hinglish)
GAP_BATCH2_MASTERDATA = {
    "master-data.alert.addAlert": (
        "Add Alert Master",
        "Alert Master जोड़ें",
        "Alert Master जोडा",
        "Alert Master add karein",
    ),
    "master-data.alert.addRecipient": (
        "Add Recipient",
        "प्राप्तकर्ता जोड़ें",
        "प्राप्तकर्ता जोडा",
        "Recipient add karein",
    ),
    "master-data.alert.addTitle": (
        "Add Alert Master",
        "Alert Master जोड़ें",
        "Alert Master जोडा",
        "Alert Master add karein",
    ),
    "master-data.alert.codePlaceholder": (
        "e.g. ALT-WARRANTY-001",
        "उदा. ALT-WARRANTY-001",
        "उदा. ALT-WARRANTY-001",
        "jaise ALT-WARRANTY-001",
    ),
    "master-data.alert.colChannels": (
        "Channels",
        "चैनल",
        "चॅनेल्स",
        "Channels",
    ),
    "master-data.alert.colCode": (
        "Code",
        "कोड",
        "कोड",
        "Code",
    ),
    "master-data.alert.colName": (
        "Name",
        "नाम",
        "नाव",
        "Name",
    ),
    "master-data.alert.confirmDeactivate": (
        'Deactivate alert "{{name}}"?',
        '"{{name}}" alert को निष्क्रिय करें?',
        '"{{name}}" alert निष्क्रिय करायचा का?',
        '"{{name}}" alert ko deactivate karein?',
    ),
    "master-data.alert.descPlaceholder": (
        "The alert's main message body...",
        "अलर्ट का मुख्य संदेश यहाँ लिखें...",
        "अलर्टचा मुख्य मेसेज मजकूर...",
        "Alert ka main message body...",
    ),
    "master-data.alert.editTitle": (
        "Edit Alert Master",
        "Alert Master संपादित करें",
        "Alert Master संपादित करा",
        "Alert Master edit karein",
    ),
    "master-data.alert.errDeactivate": (
        "Failed to deactivate Alert Master.",
        "Alert Master को निष्क्रिय करने में विफल।",
        "Alert Master निष्क्रिय करण्यात अयशस्वी.",
        "Alert Master deactivate nahi ho paaya.",
    ),
    "master-data.alert.errLoad": (
        "Could not load alert masters.",
        "Alert masters लोड नहीं हो सके।",
        "Alert masters लोड होऊ शकले नाहीत.",
        "Alert masters load nahi ho paaye.",
    ),
    "master-data.alert.errSave": (
        "Failed to save Alert Master.",
        "Alert Master सेव करने में विफल।",
        "Alert Master सेव्ह करण्यात अयशस्वी.",
        "Alert Master save nahi ho paaya.",
    ),
    "master-data.alert.errSend": (
        "Failed to send alert.",
        "अलर्ट भेजने में विफल।",
        "अलर्ट पाठवण्यात अयशस्वी.",
        "Alert send nahi ho paaya.",
    ),
    "master-data.alert.errUpdate": (
        "Failed to update Alert Master.",
        "Alert Master अपडेट करने में विफल।",
        "Alert Master अपडेट करण्यात अयशस्वी.",
        "Alert Master update nahi ho paaya.",
    ),
    "master-data.alert.formSubtitle": (
        "Author alert content and choose which channel(s) it sends through.",
        "अलर्ट की सामग्री लिखें और चुनें कि यह किन चैनल(चैनलों) के ज़रिए भेजा जाएगा।",
        "अलर्टचा मजकूर लिहा आणि तो कोणत्या चॅनेल(ल्स) मार्फत पाठवायचा ते निवडा.",
        "Alert ka content likhein aur choose karein ki ye kaunse channel(s) ke through bheja jaayega.",
    ),
    "master-data.alert.headerFooter": (
        "Header / Footer",
        "हेडर / फ़ूटर",
        "हेडर / फूटर",
        "Header / Footer",
    ),
    "master-data.alert.labelChannels": (
        "Send Via *",
        "किसके ज़रिए भेजें *",
        "कशाद्वारे पाठवायचे *",
        "Kis channel se bhejna hai *",
    ),
    "master-data.alert.labelCode": (
        "Code *",
        "कोड *",
        "कोड *",
        "Code *",
    ),
    "master-data.alert.labelFooter": (
        "Footer",
        "फ़ूटर",
        "फूटर",
        "Footer",
    ),
    "master-data.alert.labelHeader": (
        "Header",
        "हेडर",
        "हेडर",
        "Header",
    ),
    "master-data.alert.labelName": (
        "Name *",
        "नाम *",
        "नाव *",
        "Name *",
    ),
    "master-data.alert.namePlaceholder": (
        "e.g. Warranty Expiring Soon",
        "उदा. Warranty जल्द समाप्त हो रही है",
        "उदा. Warranty लवकरच संपत आहे",
        "jaise Warranty jald expire ho rahi hai",
    ),
    "master-data.alert.searchUsers": (
        "Search users...",
        "उपयोगकर्ता खोजें...",
        "वापरकर्ते शोधा...",
        "Users search karein...",
    ),
    "master-data.alert.send": (
        "Send",
        "भेजें",
        "पाठवा",
        "Send",
    ),
    "master-data.alert.sendChannels": (
        "Will send via: {{channels}}",
        "इसके ज़रिए भेजा जाएगा: {{channels}}",
        "याद्वारे पाठवले जाईल: {{channels}}",
        "Ye {{channels}} ke through bheja jaayega",
    ),
    "master-data.alert.sendTitle": (
        'Send "{{name}}"',
        '"{{name}}" भेजें',
        '"{{name}}" पाठवा',
        '"{{name}}" bhejein',
    ),
    "master-data.alert.sending": (
        "Sending...",
        "भेजा जा रहा है...",
        "पाठवले जात आहे...",
        "Bheja jaa raha hai...",
    ),
    "master-data.alert.title": (
        "Alert Masters",
        "Alert Masters",
        "Alert Masters",
        "Alert Masters",
    ),
    "master-data.alert.toastDeactivated": (
        "Alert Master deactivated.",
        "Alert Master निष्क्रिय कर दिया गया।",
        "Alert Master निष्क्रिय करण्यात आले.",
        "Alert Master deactivate ho gaya.",
    ),
    "master-data.alert.toastSaved": (
        "Alert Master saved (pending approval).",
        "Alert Master सेव हो गया (अनुमोदन लंबित)।",
        "Alert Master सेव्ह झाला (मंजुरी प्रलंबित).",
        "Alert Master save ho gaya (approval pending hai).",
    ),
    "master-data.alert.toastSent": (
        "Alert sent to {{count}} recipient(s).",
        "अलर्ट {{count}} प्राप्तकर्ता(ओं) को भेजा गया।",
        "अलर्ट {{count}} प्राप्तकर्त्यांना पाठवला गेला.",
        "Alert {{count}} recipient(s) ko bhej diya gaya.",
    ),
    "master-data.alert.toastUpdated": (
        "Alert Master updated.",
        "Alert Master अपडेट हो गया।",
        "Alert Master अपडेट झाला.",
        "Alert Master update ho gaya.",
    ),
    "master-data.template.activeNo": (
        "No",
        "नहीं",
        "नाही",
        "Nahi",
    ),
    "master-data.template.activeYes": (
        "Yes — applied",
        "हाँ — लागू है",
        "होय — लागू आहे",
        "Haan — applied hai",
    ),
    "master-data.template.addTemplate": (
        "Add Template Master",
        "Template Master जोड़ें",
        "Template Master जोडा",
        "Template Master add karein",
    ),
    "master-data.template.addTitle": (
        "Add Template Master",
        "Template Master जोड़ें",
        "Template Master जोडा",
        "Template Master add karein",
    ),
    "master-data.template.codePlaceholder": (
        "e.g. TPL-PDF-001",
        "उदा. TPL-PDF-001",
        "उदा. TPL-PDF-001",
        "jaise TPL-PDF-001",
    ),
    "master-data.template.colActive": (
        "Active For Exports",
        "Exports के लिए सक्रिय",
        "Exports साठी सक्रिय",
        "Exports ke liye Active",
    ),
    "master-data.template.colCode": (
        "Code",
        "कोड",
        "कोड",
        "Code",
    ),
    "master-data.template.colName": (
        "Name",
        "नाम",
        "नाव",
        "Name",
    ),
    "master-data.template.colType": (
        "Type",
        "प्रकार",
        "प्रकार",
        "Type",
    ),
    "master-data.template.confirmDeactivate": (
        'Deactivate template "{{name}}"?',
        '"{{name}}" template को निष्क्रिय करें?',
        '"{{name}}" template निष्क्रिय करायचा का?',
        '"{{name}}" template ko deactivate karein?',
    ),
    "master-data.template.editTitle": (
        "Edit Template Master",
        "Template Master संपादित करें",
        "Template Master संपादित करा",
        "Template Master edit karein",
    ),
    "master-data.template.errDeactivate": (
        "Failed to deactivate Template Master.",
        "Template Master को निष्क्रिय करने में विफल।",
        "Template Master निष्क्रिय करण्यात अयशस्वी.",
        "Template Master deactivate nahi ho paaya.",
    ),
    "master-data.template.errLoad": (
        "Could not load template masters.",
        "Template masters लोड नहीं हो सके।",
        "Template masters लोड होऊ शकले नाहीत.",
        "Template masters load nahi ho paaye.",
    ),
    "master-data.template.errSave": (
        "Failed to save Template Master.",
        "Template Master सेव करने में विफल।",
        "Template Master सेव्ह करण्यात अयशस्वी.",
        "Template Master save nahi ho paaya.",
    ),
    "master-data.template.errSetActive": (
        "Failed to set this template active.",
        "इस template को सक्रिय करने में विफल।",
        "हा template सक्रिय करण्यात अयशस्वी.",
        "Ye template active nahi kiya ja saka.",
    ),
    "master-data.template.errUpdate": (
        "Failed to update Template Master.",
        "Template Master अपडेट करने में विफल।",
        "Template Master अपडेट करण्यात अयशस्वी.",
        "Template Master update nahi ho paaya.",
    ),
    "master-data.template.formSubtitle": (
        "Author a header/footer applied to PDF or Excel exports app-wide.",
        "एक header/footer तैयार करें जो पूरे app में PDF या Excel exports पर लागू होगा।",
        "एक header/footer तयार करा जो संपूर्ण app मध्ये PDF किंवा Excel exports वर लागू होईल.",
        "Ek header/footer author karein jo pure app mein PDF ya Excel exports par apply hoga.",
    ),
    "master-data.template.headerFooter": (
        "Header / Footer",
        "हेडर / फ़ूटर",
        "हेडर / फूटर",
        "Header / Footer",
    ),
    "master-data.template.labelCode": (
        "Code *",
        "कोड *",
        "कोड *",
        "Code *",
    ),
    "master-data.template.labelFooter": (
        "Footer",
        "फ़ूटर",
        "फूटर",
        "Footer",
    ),
    "master-data.template.labelHeader": (
        "Header",
        "हेडर",
        "हेडर",
        "Header",
    ),
    "master-data.template.labelName": (
        "Name *",
        "नाम *",
        "नाव *",
        "Name *",
    ),
    "master-data.template.labelSubject": (
        "Subject",
        "विषय",
        "विषय",
        "Subject",
    ),
    "master-data.template.labelType": (
        "Type *",
        "प्रकार *",
        "प्रकार *",
        "Type *",
    ),
    "master-data.template.namePlaceholder": (
        "e.g. Standard PDF Branding",
        "उदा. Standard PDF Branding",
        "उदा. Standard PDF Branding",
        "jaise Standard PDF Branding",
    ),
    "master-data.template.placeholderHint": (
        "Use placeholders like {{date}}, {{user_name}} or {{record_count}} — they're resolved with real values each time someone downloads a PDF/Excel export.",
        "{{date}}, {{user_name}} या {{record_count}} जैसे placeholders का उपयोग करें — जब भी कोई PDF/Excel export डाउनलोड करता है, ये असली values से बदल दिए जाते हैं।",
        "{{date}}, {{user_name}} किंवा {{record_count}} सारखे placeholders वापरा — जेव्हा कोणी PDF/Excel export डाउनलोड करतो तेव्हा ते खऱ्या values ने बदलले जातात.",
        "{{date}}, {{user_name}} ya {{record_count}} jaise placeholders use karein — jab bhi koi PDF/Excel export download karta hai, ye real values se resolve ho jaate hain.",
    ),
    "master-data.template.setActive": (
        "Set as the active template for this type",
        "इस type के लिए इसे active template के रूप में सेट करें",
        "या type साठी हा active template म्हणून सेट करा",
        "Is type ke liye ise active template set karein",
    ),
    "master-data.template.subjectPlaceholder": (
        "Title line shown on the generated document",
        "जनरेट किए गए document पर दिखाई जाने वाली शीर्षक पंक्ति",
        "जनरेट केलेल्या document वर दिसणारी शीर्षक ओळ",
        "Generated document par dikhne wali title line",
    ),
    "master-data.template.title": (
        "Template Masters",
        "Template Masters",
        "Template Masters",
        "Template Masters",
    ),
    "master-data.template.toastDeactivated": (
        "Template Master deactivated.",
        "Template Master निष्क्रिय कर दिया गया।",
        "Template Master निष्क्रिय करण्यात आले.",
        "Template Master deactivate ho gaya.",
    ),
    "master-data.template.toastSaved": (
        "Template Master saved (pending approval).",
        "Template Master सेव हो गया (अनुमोदन लंबित)।",
        "Template Master सेव्ह झाला (मंजुरी प्रलंबित).",
        "Template Master save ho gaya (approval pending hai).",
    ),
    "master-data.template.toastSetActive": (
        '"{{name}}" is now the active {{docType}} template.',
        '"{{name}}" अब active {{docType}} template है।',
        '"{{name}}" आता active {{docType}} template आहे.',
        '"{{name}}" ab active {{docType}} template hai.',
    ),
    "master-data.template.toastUpdated": (
        "Template Master updated.",
        "Template Master अपडेट हो गया।",
        "Template Master अपडेट झाला.",
        "Template Master update ho gaya.",
    ),
    "system-config.common.status": (
        "Status",
        "स्थिति",
        "स्थिती",
        "Status",
    ),
    "system-config.dynamicFields.active": (
        "Active",
        "सक्रिय",
        "सक्रिय",
        "Active",
    ),
    "system-config.dynamicFields.inactive": (
        "Inactive",
        "निष्क्रिय",
        "निष्क्रिय",
        "Inactive",
    ),
    "system-config.dynamicFields.reactivate": (
        "Reactivate",
        "पुनः सक्रिय करें",
        "पुन्हा सक्रिय करा",
        "Reactivate karein",
    ),
    "system-config.systemConfig.channelsIntro": (
        "Email (SMTP) is already configured under System Parameters → Mail. These two toggles control whether SMS and WhatsApp are offered as alert channels.",
        "Email (SMTP) पहले से ही System Parameters → Mail के अंतर्गत कॉन्फ़िगर है। ये दो toggles नियंत्रित करते हैं कि SMS और WhatsApp को alert channels के रूप में offer किया जाए या नहीं।",
        "Email (SMTP) आधीच System Parameters → Mail अंतर्गत कॉन्फिगर केलेले आहे. हे दोन toggles नियंत्रित करतात की SMS आणि WhatsApp alert channels म्हणून द्यायचे की नाही.",
        "Email (SMTP) already System Parameters → Mail ke under configure hai. Ye do toggles control karte hain ki SMS aur WhatsApp alert channels ke roop mein offer kiye jaayein ya nahi.",
    ),
    "system-config.systemConfig.channelsStubNote": (
        "Sending is currently a logged stub — messages are recorded but not dispatched to a live gateway yet.",
        "Sending फ़िलहाल एक logged stub है — messages रिकॉर्ड होते हैं लेकिन अभी किसी live gateway पर भेजे नहीं जाते।",
        "Sending सध्या एक logged stub आहे — messages रेकॉर्ड होतात पण अजून कोणत्याही live gateway वर पाठवले जात नाहीत.",
        "Sending abhi ek logged stub hai — messages record hote hain lekin abhi kisi live gateway par dispatch nahi hote.",
    ),
    "system-config.systemConfig.loadingChannel": (
        "Loading {{title}} configuration…",
        "{{title}} configuration लोड हो रही है…",
        "{{title}} configuration लोड होत आहे…",
        "{{title}} configuration load ho rahi hai…",
    ),
    "system-config.systemConfig.sms": (
        "SMS",
        "SMS",
        "SMS",
        "SMS",
    ),
    "system-config.systemConfig.smsHint": (
        "Off = SMS is not offered as an alert channel.",
        "Off = SMS को alert channel के रूप में offer नहीं किया जाता।",
        "Off = SMS alert channel म्हणून दिले जात नाही.",
        "Off = SMS alert channel ke roop mein offer nahi hota.",
    ),
    "system-config.systemConfig.tab.notifications": (
        "Notification Channels",
        "सूचना चैनल",
        "सूचना चॅनेल्स",
        "Notification Channels",
    ),
    "system-config.systemConfig.whatsapp": (
        "WhatsApp",
        "WhatsApp",
        "WhatsApp",
        "WhatsApp",
    ),
    "system-config.systemConfig.whatsappHint": (
        "Off = WhatsApp is not offered as an alert channel.",
        "Off = WhatsApp को alert channel के रूप में offer नहीं किया जाता।",
        "Off = WhatsApp alert channel म्हणून दिले जात नाही.",
        "Off = WhatsApp alert channel ke roop mein offer nahi hota.",
    ),
    "system-config.systemConfig.whatsappProviderPlaceholder": (
        "e.g. meta-cloud, twilio",
        "उदा. meta-cloud, twilio",
        "उदा. meta-cloud, twilio",
        "jaise meta-cloud, twilio",
    ),
}


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 GAP_BATCH2_MASTERDATA.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(GAP_BATCH2_MASTERDATA)} gap-batch2-masterdata keys.")


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