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

Usage: docker compose exec api python seed_translations_pageinfo_role_detail.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_DETAIL = {
    "role-detail.title": (
        "Inspect Security Profile",
        "सुरक्षा प्रोफ़ाइल निरीक्षण",
        "सुरक्षा प्रोफाईल तपासणी",
        "Inspect Security Profile",
    ),
    "role-detail.subtitle": (
        "Read-only view of a role's real permissions and assignments",
        "किसी role की वास्तविक permissions और assignments का read-only दृश्य",
        "एखाद्या role च्या वास्तविक permissions आणि assignments चे read-only दृश्य",
        "Kisi role ki real permissions aur assignments ka read-only view",
    ),
    "role-detail.body.0": (
        "Shows exactly what a role can do: the live permission keys granted to it, grouped by module, and every user currently assigned to it. Nothing here is editable — this is an inspection screen, not the edit form.",
        "यह ठीक-ठीक दिखाता है कि कोई role क्या कर सकता है: उसे दी गई live permission keys, module के अनुसार समूहीकृत, और वे सभी users जो वर्तमान में इसे assign किए गए हैं। यहाँ कुछ भी editable नहीं है — यह एक inspection screen है, edit form नहीं।",
        "हे नेमके दाखवते की एखादी role काय करू शकते: तिला दिलेल्या live permission keys, module नुसार गटबद्ध, आणि सध्या तिला assign केलेले सर्व users. येथे काहीही editable नाही — ही एक inspection screen आहे, edit form नाही.",
        "Ye exactly dikhata hai ki koi role kya kar sakti hai: usse di gayi live permission keys, module ke hisab se grouped, aur wo sab users jo currently isse assign hain. Yahan kuch bhi editable nahi hai — ye ek inspection screen hai, edit form nahi.",
    ),
    "role-detail.body.1": (
        "Permission counts, assigned-user counts and the module groupings are computed from the role's actual data and the live Permission Catalog, so this always reflects current state, not a cached snapshot.",
        "Permission counts, assigned-user counts और module groupings role के वास्तविक data और live Permission Catalog से गणना किए जाते हैं, इसलिए यह हमेशा current state दर्शाता है, कोई cached snapshot नहीं।",
        "Permission counts, assigned-user counts आणि module groupings हे role च्या प्रत्यक्ष data आणि live Permission Catalog मधून मोजले जातात, त्यामुळे हे नेहमी current state दर्शवते, cached snapshot नाही.",
        "Permission counts, assigned-user counts aur module groupings role ke actual data aur live Permission Catalog se calculate hote hain, isliye ye hamesha current state dikhata hai, koi cached snapshot nahi.",
    ),
    "role-detail.stepsHeading": (
        "Where this fits",
        "यह कहाँ फिट बैठता है",
        "हे कुठे बसते",
        "Ye kahan fit hota hai",
    ),
    "role-detail.steps.0.label": (
        "Role Created",
        "Role बनाया गया",
        "Role तयार केली",
        "Role Create Hua",
    ),
    "role-detail.steps.0.caption": (
        "Created as System (built-in) or Custom in Role Management.",
        "Role Management में System (built-in) या Custom के रूप में बनाया गया।",
        "Role Management मध्ये System (built-in) किंवा Custom म्हणून तयार केली.",
        "Role Management mein System (built-in) ya Custom ke roop mein create hui.",
    ),
    "role-detail.steps.1.label": (
        "Permissions Mapped",
        "Permissions मैप की गईं",
        "Permissions मॅप केल्या",
        "Permissions Map Hui",
    ),
    "role-detail.steps.1.caption": (
        "Permission keys attached via Role Permissions / the Permission Catalog.",
        "Permission keys Role Permissions / Permission Catalog के माध्यम से जोड़ी जाती हैं।",
        "Permission keys Role Permissions / Permission Catalog द्वारे जोडल्या जातात.",
        "Permission keys Role Permissions / Permission Catalog ke through attach hoti hain.",
    ),
    "role-detail.steps.2.label": (
        "Users Assigned",
        "Users असाइन किए गए",
        "Users असाइन केले",
        "Users Assign Hue",
    ),
    "role-detail.steps.2.caption": (
        "Users get this role, inheriting exactly the permissions shown here.",
        "Users को यह role मिलता है, और वे ठीक वही permissions inherit करते हैं जो यहाँ दिखाई गई हैं।",
        "Users ना ही role मिळते, आणि ते इथे दाखवलेल्या नेमक्या permissions inherit करतात.",
        "Users ko ye role milta hai, aur wo exactly wahi permissions inherit karte hain jo yahan dikhayi gayi hain.",
    ),
    "role-detail.steps.3.label": (
        "Inspected Here",
        "यहाँ निरीक्षण किया गया",
        "इथे तपासणी केली",
        "Yahan Inspect Hota Hai",
    ),
    "role-detail.steps.3.caption": (
        "This page — a live, read-only audit view of the two steps above.",
        "यह page — ऊपर दिए गए दो steps का एक live, read-only audit दृश्य।",
        "हे page — वरील दोन steps चे live, read-only audit दृश्य.",
        "Ye page — upar diye gaye do steps ka ek live, read-only audit view.",
    ),
    "role-detail.fieldRules.0.name": (
        "Key Code",
        "की कोड",
        "की कोड",
        "Key Code",
    ),
    "role-detail.fieldRules.0.description": (
        "The role's stable identifier (role_id) — used in API calls and permission checks, not just a display label.",
        "Role का स्थिर पहचानकर्ता (role_id) — API calls और permission checks में उपयोग होता है, केवल display label नहीं।",
        "Role चा स्थिर ओळखकर्ता (role_id) — API calls आणि permission checks मध्ये वापरला जातो, फक्त display label नाही.",
        "Role ka stable identifier (role_id) — API calls aur permission checks mein use hota hai, sirf display label nahi.",
    ),
    "role-detail.fieldRules.1.name": (
        "Profile Type",
        "प्रोफ़ाइल प्रकार",
        "प्रोफाईल प्रकार",
        "Profile Type",
    ),
    "role-detail.fieldRules.1.description": (
        "System roles ship with the product and can't be renamed/deleted; Custom roles are tenant-defined.",
        "System roles product के साथ आते हैं और इन्हें rename/delete नहीं किया जा सकता; Custom roles tenant द्वारा परिभाषित होते हैं।",
        "System roles product सोबत येतात आणि त्यांना rename/delete करता येत नाही; Custom roles tenant द्वारे परिभाषित केले जातात.",
        "System roles product ke saath aate hain aur inhe rename/delete nahi kiya ja sakta; Custom roles tenant dwara define kiye jaate hain.",
    ),
    "role-detail.fieldRules.2.name": (
        "Permissions",
        "Permissions",
        "Permissions",
        "Permissions",
    ),
    "role-detail.fieldRules.2.description": (
        "Raw permission keys the role currently holds; unrecognized keys (not in the catalog) are grouped under \"Other\".",
        "वे raw permission keys जो role वर्तमान में रखता है; catalog में न मिलने वाली keys को \"Other\" के अंतर्गत समूहीकृत किया जाता है।",
        "role सध्या धारण करत असलेल्या raw permission keys; catalog मध्ये न सापडणाऱ्या keys \"Other\" अंतर्गत गटबद्ध केल्या जातात.",
        "Wo raw permission keys jo role currently hold karta hai; catalog mein na milne wali keys ko \"Other\" ke under grouped kiya jaata hai.",
    ),
    "role-detail.fieldRules.3.name": (
        "Assigned Users",
        "असाइन किए गए Users",
        "असाइन केलेले Users",
        "Assigned Users",
    ),
    "role-detail.fieldRules.3.description": (
        "Every user whose account currently has this role — click a row to open that user's profile.",
        "हर वह user जिसके account में वर्तमान में यह role है — उस user की profile खोलने के लिए row पर click करें।",
        "प्रत्येक तो user ज्याच्या account मध्ये सध्या ही role आहे — त्या user ची profile उघडण्यासाठी row वर click करा.",
        "Har wo user jiske account mein currently ye role hai — us user ki profile kholne ke liye row par click karein.",
    ),
    "role-detail.tip.title": (
        "Custom permission keys",
        "Custom permission keys",
        "Custom permission keys",
        "Custom permission keys",
    ),
    "role-detail.tip.body": (
        "If a permission key isn't in the live Permission Catalog (e.g. it was removed or renamed after being granted), it still shows here verbatim under \"Other\" — use that to spot stale or orphaned grants that need cleanup in Role Permissions.",
        "यदि कोई permission key live Permission Catalog में नहीं है (जैसे grant होने के बाद इसे हटा दिया गया या rename कर दिया गया), तो भी यह यहाँ \"Other\" के अंतर्गत ज्यों-का-त्यों दिखाई देती है — इसका उपयोग stale या orphaned grants को पहचानने के लिए करें जिन्हें Role Permissions में cleanup की ज़रूरत है।",
        "जर एखादी permission key live Permission Catalog मध्ये नसेल (उदा. grant झाल्यानंतर ती काढून टाकली गेली किंवा rename केली गेली), तरीही ती इथे \"Other\" अंतर्गत जशीच्या तशी दिसते — याचा वापर stale किंवा orphaned grants ओळखण्यासाठी करा ज्यांना Role Permissions मध्ये cleanup आवश्यक आहे.",
        "Agar koi permission key live Permission Catalog mein nahi hai (jaise grant hone ke baad usse remove ya rename kar diya gaya), to bhi ye yahan \"Other\" ke under verbatim dikhti hai — isse use karke wo stale ya orphaned grants spot karein jinhe Role Permissions mein cleanup ki zaroorat hai.",
    ),
}


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_DETAIL.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_DETAIL)} role-detail keys.")


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