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

Usage: docker compose exec api python seed_translations_pageinfo_roles.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)
ROLES = {
    "roles.title": (
        "Role Management",
        "भूमिका प्रबंधन",
        "भूमिका व्यवस्थापन",
        "Role Management",
    ),
    "roles.subtitle": (
        "Security profiles and the permissions each one grants",
        "सुरक्षा प्रोफ़ाइल और प्रत्येक द्वारा दी जाने वाली अनुमतियाँ",
        "सुरक्षा प्रोफाइल आणि प्रत्येकाद्वारे दिल्या जाणाऱ्या परवानग्या",
        "Security profiles aur har ek dwara diye jaane wale permissions",
    ),
    "roles.body.0": (
        "The register of security roles across the system and the permissions each one grants.",
        "सिस्टम भर में सुरक्षा भूमिकाओं और प्रत्येक द्वारा दी जाने वाली अनुमतियों का रजिस्टर।",
        "संपूर्ण सिस्टममधील सुरक्षा भूमिकांची आणि प्रत्येकाद्वारे दिल्या जाणाऱ्या परवानग्यांची नोंदवही.",
        "System bhar mein security roles aur har ek dwara diye jaane wale permissions ka register.",
    ),
    "roles.body.1": (
        "System roles ship with the platform and cannot be deleted or renamed; Custom roles are created here and can be edited, duplicated, or removed freely.",
        "System roles प्लेटफ़ॉर्म के साथ पहले से आती हैं और इन्हें डिलीट या रीनेम नहीं किया जा सकता; Custom roles यहाँ बनाई जाती हैं और इन्हें स्वतंत्र रूप से एडिट, डुप्लिकेट या हटाया जा सकता है।",
        "System roles प्लॅटफॉर्मसोबत आधीच येतात आणि त्या डिलीट किंवा रीनेम करता येत नाहीत; Custom roles येथे तयार केल्या जातात आणि त्या मुक्तपणे एडिट, डुप्लिकेट किंवा काढून टाकता येतात.",
        "System roles platform ke saath already aati hain aur inhe delete ya rename nahi kiya ja sakta; Custom roles yahan create hoti hain aur inhe freely edit, duplicate, ya remove kiya ja sakta hai.",
    ),
    "roles.stepsHeading": (
        "How a role is built",
        "एक भूमिका कैसे बनाई जाती है",
        "एक भूमिका कशी तयार केली जाते",
        "Ek role kaise banta hai",
    ),
    "roles.steps.0.label": ("Create", "बनाएँ", "तयार करा", "Create"),
    "roles.steps.0.caption": (
        "Name the role and pick its permissions from the module catalog.",
        "भूमिका को नाम दें और module catalog से इसकी अनुमतियाँ चुनें।",
        "भूमिकेला नाव द्या आणि module catalog मधून तिच्या परवानग्या निवडा.",
        "Role ko naam dein aur module catalog se uski permissions choose karein.",
    ),
    "roles.steps.1.label": ("Assign", "असाइन करें", "असाइन करा", "Assign"),
    "roles.steps.1.caption": (
        "Attach the role to users on the Users page — permissions apply automatically.",
        "Users पेज पर users को भूमिका से जोड़ें — अनुमतियाँ स्वतः लागू हो जाती हैं।",
        "Users पेजवर users ला भूमिकेशी जोडा — परवानग्या आपोआप लागू होतात.",
        "Users page par users ko role se attach karein — permissions automatically apply ho jaati hain.",
    ),
    "roles.steps.2.label": ("Refine", "परिष्कृत करें", "सुधारित करा", "Refine"),
    "roles.steps.2.caption": (
        "Use Manage Permissions to add or remove access as needs change.",
        "आवश्यकताओं में बदलाव के अनुसार पहुँच जोड़ने या हटाने के लिए Manage Permissions का उपयोग करें।",
        "गरजा बदलल्यानुसार access जोडण्यासाठी किंवा काढण्यासाठी Manage Permissions वापरा.",
        "Zaroorat badalne par access add ya remove karne ke liye Manage Permissions use karein.",
    ),
    "roles.steps.3.label": ("Retire", "निष्क्रिय करें", "निवृत्त करा", "Retire"),
    "roles.steps.3.caption": (
        "Deactivate a role to block new assignments, or delete a Custom role once unused.",
        "नए assignments को रोकने के लिए किसी भूमिका को Deactivate करें, या उपयोग में न होने पर किसी Custom role को डिलीट करें।",
        "नवीन assignments रोखण्यासाठी एखादी भूमिका Deactivate करा, किंवा वापरात नसल्यास एखादी Custom role डिलीट करा.",
        "Naye assignments rokne ke liye role ko deactivate karein, ya use mein na hone par Custom role ko delete kar dein.",
    ),
    "roles.fieldRules.0.name": ("Role Name", "भूमिका का नाम", "भूमिकेचे नाव", "Role Name"),
    "roles.fieldRules.0.description": (
        "Unique label for the role; locked for System roles once created.",
        "भूमिका के लिए विशिष्ट लेबल; बनने के बाद System roles के लिए यह लॉक हो जाता है।",
        "भूमिकेसाठी युनिक लेबल; तयार झाल्यानंतर System roles साठी हे लॉक होते.",
        "Role ke liye unique label; create hone ke baad System roles ke liye ye lock ho jaata hai.",
    ),
    "roles.fieldRules.1.name": ("Description", "विवरण", "वर्णन", "Description"),
    "roles.fieldRules.1.description": (
        "One-line summary of what the role is for — required on edit.",
        "भूमिका किस लिए है इसका एक-पंक्ति सारांश — edit करते समय आवश्यक।",
        "भूमिका कशासाठी आहे याचा एक-ओळीचा सारांश — edit करताना आवश्यक.",
        "Role kis liye hai iska ek-line summary — edit karte waqt required hota hai.",
    ),
    "roles.fieldRules.2.name": ("Permissions", "अनुमतियाँ", "परवानग्या", "Permissions"),
    "roles.fieldRules.2.description": (
        "Checkbox selections grouped by module; grants exactly the actions listed.",
        "module के अनुसार समूहित checkbox चयन; सूचीबद्ध actions को बिल्कुल वैसा ही प्रदान करता है।",
        "module नुसार गटबद्ध केलेल्या checkbox निवडी; सूचीबद्ध actions नेमक्या तशाच प्रदान करते.",
        "Module ke hisaab se grouped checkbox selections; listed actions ko exactly wahi grant karta hai.",
    ),
    "roles.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "roles.fieldRules.3.description": (
        "Active roles can be assigned to users; Inactive roles are hidden from assignment.",
        "Active roles को users को असाइन किया जा सकता है; Inactive roles असाइनमेंट से छिपी रहती हैं।",
        "Active roles users ला असाइन करता येतात; Inactive roles असाइनमेंटमधून लपवल्या जातात.",
        "Active roles ko users ko assign kiya ja sakta hai; Inactive roles assignment se hidden rehti hain.",
    ),
    "roles.tip.title": (
        "Deleting is Custom-only",
        "डिलीट करना केवल Custom roles के लिए संभव है",
        "डिलीट करणे फक्त Custom roles साठीच शक्य आहे",
        "Delete karna sirf Custom roles ke liye hi possible hai",
    ),
    "roles.tip.body": (
        "System roles can never be deleted, even by Super Admin — only their description and Active/Inactive status can change. If you need to remove access entirely, duplicate the role as Custom first, then delete the copy.",
        "System roles को कभी भी डिलीट नहीं किया जा सकता, यहाँ तक कि Super Admin द्वारा भी नहीं — केवल उनका विवरण और Active/Inactive स्थिति बदली जा सकती है। यदि आपको पहुँच पूरी तरह हटानी है, तो पहले भूमिका को Custom के रूप में डुप्लिकेट करें, फिर उस कॉपी को डिलीट करें।",
        "System roles कधीही डिलीट करता येत नाहीत, अगदी Super Admin कडूनही नाही — फक्त त्यांचे वर्णन आणि Active/Inactive स्थिती बदलता येते. जर तुम्हाला access पूर्णपणे काढून टाकायचा असेल, तर आधी भूमिकेला Custom म्हणून डुप्लिकेट करा, नंतर ती कॉपी डिलीट करा.",
        "System roles kabhi bhi delete nahi ho sakti, Super Admin ke through bhi nahi — sirf inka description aur Active/Inactive status change ho sakta hai. Agar access poori tarah remove karna hai, to pehle role ko Custom ke roop mein duplicate karein, phir us copy ko delete kar dein.",
    ),
}


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 ROLES.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(ROLES)} roles keys.")


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