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

Usage: docker compose exec api python seed_translations_pageinfo_user_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)
USER_DETAIL = {
    "user-detail.title": (
        "User Details",
        "उपयोगकर्ता विवरण",
        "वापरकर्ता तपशील",
        "User Details",
    ),
    "user-detail.subtitle": (
        "Read-only profile with role assignment",
        "role assignment के साथ केवल-पठनीय प्रोफ़ाइल",
        "role assignment सह फक्त-वाचनीय प्रोफाइल",
        "Role assignment ke saath read-only profile",
    ),
    "user-detail.body.0": (
        "Identity, HR/contact and status attributes here are read-only — they mirror what was captured at create/edit time. Use the Edit User button to change them.",
        "यहाँ Identity, HR/contact और status attributes केवल-पठनीय हैं — ये create/edit के समय दर्ज की गई जानकारी को दर्शाते हैं। इन्हें बदलने के लिए Edit User बटन का उपयोग करें।",
        "येथील Identity, HR/contact आणि status attributes फक्त-वाचनीय आहेत — ते create/edit वेळी नोंदवलेली माहिती दर्शवतात. ती बदलण्यासाठी Edit User बटण वापरा.",
        "Yahan Identity, HR/contact aur status attributes read-only hain — ye create/edit ke time capture ki gayi info ko mirror karte hain. Inhe change karne ke liye Edit User button use karein.",
    ),
    "user-detail.body.1": (
        "The two panels on the right let you manage this account's RBAC role assignments and review the linked audit/security posture without leaving this page.",
        "दाईं ओर के दो panels आपको इस account की RBAC role assignments प्रबंधित करने और linked audit/security posture की समीक्षा इसी page से करने देते हैं।",
        "उजवीकडील दोन panels तुम्हाला या account च्या RBAC role assignments व्यवस्थापित करण्यास आणि linked audit/security posture चे पुनरावलोकन याच page वरून करण्यास मदत करतात.",
        "Right side ke do panels aapko is account ki RBAC role assignments manage karne aur linked audit/security posture ko isi page se review karne dete hain.",
    ),
    "user-detail.stepsHeading": (
        "What you can do here",
        "यहाँ आप क्या कर सकते हैं",
        "तुम्ही येथे काय करू शकता",
        "Yahan aap kya kar sakte hain",
    ),
    "user-detail.steps.0.label": ("Review Profile", "प्रोफ़ाइल की समीक्षा करें", "प्रोफाइलचे पुनरावलोकन करा", "Profile Review Karein"),
    "user-detail.steps.0.caption": (
        "Identity, HR and status fields are display-only.",
        "Identity, HR और status fields केवल-प्रदर्शन (display-only) हैं।",
        "Identity, HR आणि status fields फक्त-प्रदर्शनासाठी (display-only) आहेत.",
        "Identity, HR aur status fields sirf display-only hain.",
    ),
    "user-detail.steps.1.label": ("Assign Role", "Role असाइन करें", "Role नियुक्त करा", "Role Assign Karein"),
    "user-detail.steps.1.caption": (
        "Pick a role from the dropdown, then click Assign.",
        "dropdown से एक role चुनें, फिर Assign पर क्लिक करें।",
        "dropdown मधून एक role निवडा, नंतर Assign वर क्लिक करा.",
        "Dropdown se ek role pick karein, phir Assign par click karein.",
    ),
    "user-detail.steps.2.label": ("Remove Role", "Role हटाएँ", "Role काढून टाका", "Role Remove Karein"),
    "user-detail.steps.2.caption": (
        "Click the x on a role badge to revoke it instantly.",
        "role badge पर मौजूद x पर क्लिक करके इसे तुरंत revoke करें।",
        "role badge वरील x वर क्लिक करून ते त्वरित revoke करा.",
        "Role badge par x par click karke usse turant revoke karein.",
    ),
    "user-detail.steps.3.label": ("Escalate Issues", "समस्याओं को एस्केलेट करें", "समस्या एस्कलेट करा", "Issues Escalate Karein"),
    "user-detail.steps.3.caption": (
        "Report credential mismatches to SecOps per the notice below.",
        "नीचे दिए गए notice के अनुसार credential mismatches की सूचना SecOps को दें।",
        "खालील notice नुसार credential mismatches बद्दल SecOps ला कळवा.",
        "Neeche diye gaye notice ke hisaab se credential mismatches SecOps ko report karein.",
    ),
    "user-detail.fieldRules.0.name": (
        "Select role to assign",
        "असाइन करने के लिए Role चुनें",
        "नियुक्त करण्यासाठी Role निवडा",
        "Assign karne ke liye Role Select Karein",
    ),
    "user-detail.fieldRules.0.description": (
        "The only required input on this page — Assign stays disabled until a role is picked.",
        "इस page पर एकमात्र आवश्यक input — जब तक कोई role नहीं चुना जाता, Assign disabled रहता है।",
        "या page वरील एकमेव आवश्यक input — role निवडेपर्यंत Assign disabled राहते.",
        "Is page par sirf yahi required input hai — jab tak role select nahi hota, Assign disabled rehta hai.",
    ),
    "user-detail.fieldRules.1.name": ("Assigned Role", "Assigned Role", "Assigned Role", "Assigned Role"),
    "user-detail.fieldRules.1.description": (
        "The user's base/primary role badge; change it from the Edit User page, not here.",
        "उपयोगकर्ता का base/primary role badge; इसे यहाँ से नहीं बल्कि Edit User page से बदलें।",
        "वापरकर्त्याचा base/primary role badge; तो येथून नाही तर Edit User page वरून बदला.",
        "User ka base/primary role badge hai; ise yahan se nahi, Edit User page se change karein.",
    ),
    "user-detail.fieldRules.2.name": (
        "Assigned Roles (sidebar)",
        "Assigned Roles (sidebar)",
        "Assigned Roles (sidebar)",
        "Assigned Roles (sidebar)",
    ),
    "user-detail.fieldRules.2.description": (
        "Additional RBAC roles layered on top of the base role; add/remove independently of it.",
        "base role के ऊपर जोड़ी गई अतिरिक्त RBAC roles; इन्हें base role से स्वतंत्र रूप से add/remove करें।",
        "base role वर layered केलेल्या अतिरिक्त RBAC roles; त्या base role पासून स्वतंत्रपणे add/remove करा.",
        "Base role ke upar layered additional RBAC roles hain; inhe base role se independently add/remove karein.",
    ),
    "user-detail.fieldRules.3.name": ("Status", "Status", "Status", "Status"),
    "user-detail.fieldRules.3.description": (
        "Active/Inactive login-access flag, color-coded; changed only via Edit User.",
        "Active/Inactive login-access flag, color-coded; इसे केवल Edit User के माध्यम से बदला जाता है।",
        "Active/Inactive login-access flag, color-coded; तो फक्त Edit User द्वारेच बदलला जातो.",
        "Active/Inactive login-access flag hai, color-coded; ise sirf Edit User ke through hi change kiya jaata hai.",
    ),
    "user-detail.fieldRules.4.name": (
        "HR & Contact fields",
        "HR और Contact fields",
        "HR आणि Contact fields",
        "HR & Contact fields",
    ),
    "user-detail.fieldRules.4.description": (
        'Department, designation, org unit, etc.; shows "Not set" rather than a blank cell when empty.',
        'Department, designation, org unit, आदि; खाली होने पर blank cell के बजाय "Not set" दिखाता है।',
        'Department, designation, org unit, इत्यादी; रिकामे असल्यास blank cell ऐवजी "Not set" दाखवते.',
        'Department, designation, org unit, etc.; empty hone par blank cell ki jagah "Not set" dikhata hai.',
    ),
    "user-detail.tip.title": (
        "Two role systems, not one",
        "एक नहीं, दो role systems",
        "एक नाही, दोन role systems",
        "Ek nahi, do role systems",
    ),
    "user-detail.tip.body": (
        'The "Assigned Role" badge is the base role and only changes on the Edit User page. The "Assigned Roles" list on the right is a separate RBAC layer — removing every role there does not touch the base role, so the user keeps its base-role permissions.',
        '"Assigned Role" badge base role है और यह केवल Edit User page पर बदलता है। दाईं ओर की "Assigned Roles" सूची एक अलग RBAC layer है — वहाँ से सभी roles हटाने पर भी base role प्रभावित नहीं होता, इसलिए उपयोगकर्ता के पास base-role permissions बने रहते हैं।',
        '"Assigned Role" badge हा base role आहे आणि तो फक्त Edit User page वर बदलतो. उजवीकडील "Assigned Roles" यादी ही एक वेगळी RBAC layer आहे — तेथून सर्व roles काढल्यासही base role वर परिणाम होत नाही, त्यामुळे वापरकर्त्याकडे base-role permissions कायम राहतात.',
        '"Assigned Role" badge base role hai aur ye sirf Edit User page par change hota hai. Right side ki "Assigned Roles" list ek alag RBAC layer hai — wahan se sabhi roles remove karne par bhi base role par asar nahi padta, isliye user ke paas base-role permissions bane rehte 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 USER_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(USER_DETAIL)} user-detail keys.")


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