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

Usage: docker compose exec api python seed_translations_pageinfo_user_profile.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_PROFILE = {
    "user-profile.title": (
        "My Profile",
        "मेरी प्रोफ़ाइल",
        "माझी प्रोफाइल",
        "My Profile",
    ),
    "user-profile.subtitle": (
        "Your account, security & activity",
        "आपका अकाउंट, सुरक्षा और गतिविधि",
        "तुमचे अकाउंट, सुरक्षा आणि अ‍ॅक्टिव्हिटी",
        "Aapka account, security aur activity",
    ),
    "user-profile.body.0": (
        "Personal Information (name, designation, department, employment date) is HR-managed and read-only here — only Administration can change it. Contact Registers (phone, office extension, desk location) are yours to edit directly.",
        "Personal Information (नाम, पदनाम, विभाग, नियुक्ति तिथि) HR द्वारा प्रबंधित है और यहाँ केवल पढ़ने के लिए है — इसे केवल Administration ही बदल सकता है। Contact Registers (फ़ोन, ऑफिस एक्सटेंशन, डेस्क लोकेशन) आप सीधे edit कर सकते हैं।",
        "Personal Information (नाव, पदनाम, विभाग, नियुक्ती तारीख) HR द्वारे व्यवस्थापित आहे आणि येथे फक्त वाचण्यासाठी आहे — ते फक्त Administration बदलू शकते. Contact Registers (फोन, ऑफिस एक्सटेंशन, डेस्क लोकेशन) तुम्ही थेट edit करू शकता.",
        "Personal Information (naam, designation, department, employment date) HR-managed hai aur yahan sirf read-only hai — ise sirf Administration hi change kar sakta hai. Contact Registers (phone, office extension, desk location) aap directly edit kar sakte hain.",
    ),
    "user-profile.body.1": (
        "Account Security lets you enable MFA, change your password, and review your own recent logins and audit activity — none of this affects other users.",
        "Account Security से आप MFA enable कर सकते हैं, अपना password बदल सकते हैं, और अपने हाल के logins तथा audit activity को देख सकते हैं — इनमें से कुछ भी अन्य users को प्रभावित नहीं करता।",
        "Account Security मुळे तुम्ही MFA enable करू शकता, तुमचा password बदलू शकता, आणि तुमचे अलीकडील logins तसेच audit activity पाहू शकता — यापैकी काहीही इतर users वर परिणाम करत नाही.",
        "Account Security se aap MFA enable kar sakte hain, apna password change kar sakte hain, aur apne recent logins aur audit activity review kar sakte hain — inmein se kuch bhi other users ko affect nahi karta.",
    ),
    "user-profile.stepsHeading": (
        "The three tabs",
        "तीन टैब",
        "तीन टॅब्स",
        "Teen tabs",
    ),
    "user-profile.steps.0.label": ("Overview", "अवलोकन", "आढावा", "Overview"),
    "user-profile.steps.0.caption": (
        "Profile details, contact editing, MFA, password, recent logins",
        "Profile विवरण, contact editing, MFA, password, हाल के logins",
        "Profile तपशील, contact editing, MFA, password, अलीकडील logins",
        "Profile details, contact editing, MFA, password, recent logins",
    ),
    "user-profile.steps.1.label": ("Permissions", "अनुमतियाँ", "परवानग्या", "Permissions"),
    "user-profile.steps.1.caption": (
        "Read-only view of what your active role can do, grouped by module",
        "आपकी active role क्या कर सकती है, इसका read-only दृश्य, module के अनुसार समूहीकृत",
        "तुमची active role काय करू शकते याचे read-only दृश्य, module नुसार गटबद्ध",
        "Aapki active role kya kar sakti hai uska read-only view, module ke hisaab se grouped",
    ),
    "user-profile.steps.2.label": ("Security Logs", "सुरक्षा लॉग", "सुरक्षा लॉग्स", "Security Logs"),
    "user-profile.steps.2.caption": (
        "Your own recent account audit events — not other users'",
        "आपके अपने अकाउंट के हाल के audit events — अन्य users के नहीं",
        "तुमच्या स्वतःच्या अकाउंटचे अलीकडील audit events — इतर users चे नाहीत",
        "Aapke apne account ke recent audit events — other users ke nahi",
    ),
    "user-profile.fieldRules.0.name": ("Current Password", "वर्तमान पासवर्ड", "सध्याचा पासवर्ड", "Current Password"),
    "user-profile.fieldRules.0.description": (
        "Checked against your stored hash — a wrong value blocks the change.",
        "आपके stored hash के विरुद्ध जाँचा जाता है — गलत मान होने पर बदलाव रुक जाता है।",
        "तुमच्या stored hash विरुद्ध तपासले जाते — चुकीचे मूल्य असल्यास बदल रोखला जातो.",
        "Aapke stored hash ke against check hota hai — galat value hone par change block ho jaata hai.",
    ),
    "user-profile.fieldRules.1.name": ("New Password", "नया पासवर्ड", "नवीन पासवर्ड", "New Password"),
    "user-profile.fieldRules.1.description": (
        "Minimum 8 characters, and cannot be identical to your current password.",
        "न्यूनतम 8 characters होने चाहिए, और यह आपके current password के समान नहीं हो सकता।",
        "किमान 8 characters असणे आवश्यक आहे, आणि ते तुमच्या current password सारखे असू शकत नाही.",
        "Minimum 8 characters chahiye, aur ye aapke current password jaisa same nahi ho sakta.",
    ),
    "user-profile.fieldRules.2.name": (
        "6-Digit Authenticator Code",
        "6-अंकीय Authenticator कोड",
        "6-अंकी Authenticator कोड",
        "6-Digit Authenticator Code",
    ),
    "user-profile.fieldRules.2.description": (
        "Proves you scanned the QR before MFA is committed to your account — nothing is saved on 'Set Up MFA' alone.",
        "यह साबित करता है कि MFA आपके अकाउंट में commit होने से पहले आपने QR स्कैन किया था — केवल 'Set Up MFA' पर क्लिक करने से कुछ भी save नहीं होता।",
        "हे सिद्ध करते की MFA तुमच्या अकाउंटमध्ये commit होण्यापूर्वी तुम्ही QR scan केला होता — फक्त 'Set Up MFA' वर क्लिक केल्याने काहीही save होत नाही.",
        "Ye prove karta hai ki MFA aapke account mein commit hone se pehle aapne QR scan kiya tha — sirf 'Set Up MFA' par click karne se kuch bhi save nahi hota.",
    ),
    "user-profile.fieldRules.3.name": (
        "Direct Mobile / Extension / Desk Location",
        "डायरेक्ट मोबाइल / एक्सटेंशन / डेस्क लोकेशन",
        "डायरेक्ट मोबाइल / एक्सटेंशन / डेस्क लोकेशन",
        "Direct Mobile / Extension / Desk Location",
    ),
    "user-profile.fieldRules.3.description": (
        "Optional — the only fields you can self-edit; everything else in Personal Information is set by Administration.",
        "वैकल्पिक — ये एकमात्र fields हैं जिन्हें आप स्वयं edit कर सकते हैं; Personal Information में बाकी सब कुछ Administration द्वारा सेट किया जाता है।",
        "पर्यायी — हे एकमेव fields आहेत जे तुम्ही स्वतः edit करू शकता; Personal Information मधील बाकी सर्व काही Administration द्वारे सेट केले जाते.",
        "Optional — ye sirf wahi fields hain jinhe aap khud edit kar sakte hain; Personal Information mein baaki sab kuch Administration set karta hai.",
    ),
    "user-profile.tip.title": (
        "Recovery codes shown once",
        "Recovery codes केवल एक बार दिखाए जाते हैं",
        "Recovery codes फक्त एकदाच दाखवले जातात",
        "Recovery codes sirf ek baar dikhaye jaate hain",
    ),
    "user-profile.tip.body": (
        "After you verify the 6-digit code, MFA recovery codes are displayed exactly one time. Save them before clicking \"I've saved these codes\" — if you lose them, the only way to get a fresh set is to disable and re-enable MFA.",
        "6-अंकीय कोड verify करने के बाद, MFA recovery codes ठीक एक बार दिखाए जाते हैं। \"I've saved these codes\" पर क्लिक करने से पहले इन्हें save कर लें — यदि आप इन्हें खो देते हैं, तो नया सेट पाने का एकमात्र तरीका MFA को disable करके फिर से enable करना है।",
        "6-अंकी कोड verify केल्यानंतर, MFA recovery codes अगदी एकदाच दाखवले जातात. \"I've saved these codes\" वर क्लिक करण्यापूर्वी ते save करा — जर तुम्ही ते गमावले, तर नवीन सेट मिळवण्याचा एकमेव मार्ग म्हणजे MFA disable करून पुन्हा enable करणे.",
        "6-digit code verify karne ke baad, MFA recovery codes exactly ek baar dikhaye jaate hain. \"I've saved these codes\" par click karne se pehle inhe save kar lein — agar aap inhe lose kar dete hain, to naya set paane ka ek hi tarika hai MFA ko disable karke dobara enable karna.",
    ),
}


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_PROFILE.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_PROFILE)} user-profile keys.")


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