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

Usage: docker compose exec api python seed_translations_pageinfo_role_permissions_edit.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)
ROLE_PERMISSIONS_EDIT = {
    "role-permissions-edit.title": (
        "Edit Permissions",
        "अनुमतियाँ संपादित करें",
        "परवानग्या संपादित करा",
        "Edit Permissions",
    ),
    "role-permissions-edit.subtitle": (
        "Grant or revoke the exact permission keys this role holds",
        "इस role के पास मौजूद ठीक वही permission keys grant या revoke करें",
        "या role कडे असलेल्या नेमक्या permission keys grant किंवा revoke करा",
        "Is role ke paas jo exact permission keys hain unhe grant ya revoke karein",
    ),
    "role-permissions-edit.body.0": (
        "This page loads the role's currently assigned permissions alongside the full permission catalog, grouped by module. Toggle any key on or off, or add a custom key that isn't in the catalog yet.",
        "यह पेज role की वर्तमान में असाइन की गई permissions को पूरे permission catalog के साथ लोड करता है, module के अनुसार समूहित। किसी भी key को on या off करने के लिए toggle करें, या कोई custom key जोड़ें जो अभी catalog में नहीं है।",
        "हे पेज role ला सध्या असाइन केलेल्या permissions पूर्ण permission catalog सह लोड करते, module नुसार गटबद्ध. कोणतीही key on किंवा off करण्यासाठी toggle करा, किंवा एखादी custom key जोडा जी अजून catalog मध्ये नाही.",
        "Ye page role ki abhi assigned permissions ko poore permission catalog ke saath load karta hai, module ke hisaab se grouped. Kisi bhi key ko on ya off karne ke liye toggle karein, ya ek custom key add karein jo abhi catalog mein nahi hai.",
    ),
    "role-permissions-edit.body.1": (
        "Nothing changes on the server until you click Update Permissions — the Live Payload Preview panel shows the exact request body that will be sent.",
        "जब तक आप Update Permissions पर क्लिक नहीं करते, तब तक server पर कुछ भी नहीं बदलता — Live Payload Preview पैनल वह exact request body दिखाता है जो भेजी जाएगी।",
        "जोपर्यंत तुम्ही Update Permissions वर क्लिक करत नाही, तोपर्यंत server वर काहीही बदलत नाही — Live Payload Preview पॅनल जी exact request body पाठवली जाईल ती दाखवते.",
        "Jab tak aap Update Permissions par click nahi karte, tab tak server par kuch nahi badalta — Live Payload Preview panel wo exact request body dikhata hai jo bheji jaayegi.",
    ),
    "role-permissions-edit.stepsHeading": (
        "How it works",
        "यह कैसे काम करता है",
        "हे कसे कार्य करते",
        "Ye kaise kaam karta hai",
    ),
    "role-permissions-edit.steps.0.label": (
        "Load Catalog", "कैटलॉग लोड करें", "कॅटलॉग लोड करा", "Load Catalog",
    ),
    "role-permissions-edit.steps.0.caption": (
        "Fetches the role's current permissions plus every available key, grouped by module.",
        "role की current permissions और हर उपलब्ध key लाता है, module के अनुसार समूहित।",
        "role च्या current permissions आणि प्रत्येक उपलब्ध key आणते, module नुसार गटबद्ध.",
        "Role ki current permissions aur har available key fetch karta hai, module ke hisaab se grouped.",
    ),
    "role-permissions-edit.steps.1.label": (
        "Toggle Permissions", "Permissions टॉगल करें", "Permissions टॉगल करा", "Permissions Toggle Karein",
    ),
    "role-permissions-edit.steps.1.caption": (
        "Check or uncheck keys per module, or use Select All / Clear All.",
        "हर module में keys को check या uncheck करें, या Select All / Clear All का उपयोग करें।",
        "प्रत्येक module मध्ये keys check किंवा uncheck करा, किंवा Select All / Clear All वापरा.",
        "Har module mein keys ko check ya uncheck karein, ya Select All / Clear All use karein.",
    ),
    "role-permissions-edit.steps.2.label": (
        "Add Custom Key", "Custom Key जोड़ें", "Custom Key जोडा", "Custom Key Add Karein",
    ),
    "role-permissions-edit.steps.2.caption": (
        "Optional: grant a key not in the catalog by typing it and clicking Add.",
        "वैकल्पिक: catalog में मौजूद न होने वाली किसी key को टाइप करके और Add पर क्लिक करके grant करें।",
        "पर्यायी: catalog मध्ये नसलेली एखादी key टाईप करून आणि Add वर क्लिक करून grant करा.",
        "Optional: catalog mein na hone wali koi key type karke aur Add par click karke grant karein.",
    ),
    "role-permissions-edit.steps.3.label": (
        "Save", "सेव करें", "सेव्ह करा", "Save Karein",
    ),
    "role-permissions-edit.steps.3.caption": (
        "Update Permissions submits the full list, replacing the role's previous set entirely.",
        "Update Permissions पूरी सूची सबमिट करता है, जो role के पिछले सेट को पूरी तरह से बदल देता है।",
        "Update Permissions संपूर्ण यादी सबमिट करते, जी role च्या मागील सेटला पूर्णपणे बदलते.",
        "Update Permissions poori list submit karta hai, jo role ke previous set ko poori tarah replace kar deta hai.",
    ),
    "role-permissions-edit.fieldRules.0.name": (
        "Permissions Matrix", "परमिशन्स मैट्रिक्स", "परमिशन्स मॅट्रिक्स", "Permissions Matrix",
    ),
    "role-permissions-edit.fieldRules.0.description": (
        "Checkboxes grouped by module; a checked box means the role holds that permission key.",
        "module के अनुसार समूहित checkboxes; एक checked box का मतलब है कि role के पास वह permission key है।",
        "module नुसार गटबद्ध checkboxes; एक checked box म्हणजे role कडे ती permission key आहे.",
        "Module ke hisaab se grouped checkboxes; ek checked box ka matlab hai role ke paas wo permission key hai.",
    ),
    "role-permissions-edit.fieldRules.1.name": (
        "Add Custom Permission Key", "Custom Permission Key जोड़ें", "Custom Permission Key जोडा", "Add Custom Permission Key",
    ),
    "role-permissions-edit.fieldRules.1.description": (
        "Free-text field for granting a key outside the catalog; Add stays disabled until you type something, and duplicate keys are rejected.",
        "catalog के बाहर की कोई key grant करने के लिए free-text फ़ील्ड; जब तक आप कुछ टाइप नहीं करते, Add डिसेबल्ड रहता है, और duplicate keys को reject कर दिया जाता है।",
        "catalog बाहेरील एखादी key grant करण्यासाठी free-text फील्ड; जोपर्यंत तुम्ही काहीतरी टाईप करत नाही, Add डिसेबल्ड राहते, आणि duplicate keys reject केल्या जातात.",
        "Catalog ke bahar ki koi key grant karne ke liye free-text field; jab tak aap kuch type nahi karte, Add disabled rehta hai, aur duplicate keys reject ho jaati hain.",
    ),
    "role-permissions-edit.fieldRules.2.name": (
        "Custom Entries", "Custom Entries", "Custom Entries", "Custom Entries",
    ),
    "role-permissions-edit.fieldRules.2.description": (
        "Keys you added manually show in their own group with a trash icon to remove them before saving.",
        "आपके द्वारा मैन्युअल रूप से जोड़ी गई keys अपने अलग group में trash icon के साथ दिखती हैं, ताकि सेव करने से पहले उन्हें हटाया जा सके।",
        "तुम्ही manually जोडलेल्या keys त्यांच्या स्वतःच्या group मध्ये trash icon सह दिसतात, जेणेकरून सेव्ह करण्यापूर्वी त्या काढता येतील.",
        "Aapne manually add ki hui keys apne alag group mein trash icon ke saath dikhti hain, taaki save karne se pehle unhe remove kiya ja sake.",
    ),
    "role-permissions-edit.fieldRules.3.name": (
        "Selected Keys / Total", "Selected Keys / Total", "Selected Keys / Total", "Selected Keys / Total",
    ),
    "role-permissions-edit.fieldRules.3.description": (
        "Read-only live count and tag list of everything currently selected — updates as you toggle, not editable directly.",
        "वर्तमान में selected हर चीज़ की read-only live count और tag list — जैसे-जैसे आप toggle करते हैं वैसे-वैसे अपडेट होती है, सीधे editable नहीं है।",
        "सध्या selected असलेल्या प्रत्येक गोष्टीची read-only live count आणि tag list — तुम्ही toggle करता तसतशी अपडेट होते, थेट editable नाही.",
        "Abhi selected har cheez ki read-only live count aur tag list — jaise-jaise aap toggle karte hain waise-waise update hoti hai, directly editable nahi hai.",
    ),
    "role-permissions-edit.tip.title": (
        "Save replaces, not merges",
        "Save रिप्लेस करता है, मर्ज नहीं",
        "Save रिप्लेस करते, मर्ज करत नाही",
        "Save replace karta hai, merge nahi",
    ),
    "role-permissions-edit.tip.body": (
        "Update Permissions overwrites the role's entire permission list — it is not additive. Unchecking a box (or hitting Clear All) and saving removes that access immediately, even if you only meant to change one permission.",
        "Update Permissions role की पूरी permission list को overwrite कर देता है — यह additive नहीं है। किसी box को uncheck करके (या Clear All दबाकर) सेव करने पर वह access तुरंत हट जाता है, भले ही आपका इरादा केवल एक permission बदलने का हो।",
        "Update Permissions role च्या संपूर्ण permission list ला overwrite करते — हे additive नाही. एखादा box uncheck करून (किंवा Clear All दाबून) सेव्ह केल्यास तो access लगेच काढला जातो, जरी तुम्हाला फक्त एकच permission बदलायची असेल तरी.",
        "Update Permissions role ki poori permission list ko overwrite kar deta hai — ye additive nahi hai. Kisi box ko uncheck karke (ya Clear All dabakar) save karne par wo access turant hat jaata hai, chahe aapka irada sirf ek permission change karne ka ho.",
    ),
}


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 ROLE_PERMISSIONS_EDIT.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(ROLE_PERMISSIONS_EDIT)} role-permissions-edit keys.")


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