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

Usage: docker compose exec api python seed_translations_pageinfo_users_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)
USERS_EDIT = {
    "users-edit.title": (
        "Edit User",
        "उपयोगकर्ता संपादित करें",
        "वापरकर्ता संपादित करा",
        "User Edit Karein",
    ),
    "users-edit.subtitle": (
        "Update profile, HR details, role and password for one directory account",
        "एक directory account के लिए प्रोफ़ाइल, HR विवरण, role और password अपडेट करें",
        "एका directory account साठी प्रोफाइल, HR तपशील, role आणि password अपडेट करा",
        "Ek directory account ke liye profile, HR details, role aur password update karein",
    ),
    "users-edit.body.0": (
        "Update account details, role assignments, and directory status for the selected enterprise user.",
        "चयनित enterprise user के लिए account विवरण, role assignments और directory status अपडेट करें।",
        "निवडलेल्या enterprise user साठी account तपशील, role assignments आणि directory status अपडेट करा.",
        "Selected enterprise user ke liye account details, role assignments, aur directory status update karein.",
    ),
    "users-edit.stepsHeading": (
        "How editing works",
        "संपादन कैसे काम करता है",
        "संपादन कसे कार्य करते",
        "Editing kaise kaam karta hai",
    ),
    "users-edit.steps.0.label": ("Core Profile", "मुख्य प्रोफ़ाइल", "मुख्य प्रोफाइल", "Core Profile"),
    "users-edit.steps.0.caption": (
        "Name, email, role and Active/Inactive status — the account fundamentals.",
        "नाम, email, role और Active/Inactive status — account की बुनियादी बातें।",
        "नाव, email, role आणि Active/Inactive status — account च्या मूलभूत बाबी.",
        "Naam, email, role aur Active/Inactive status — account ke fundamentals.",
    ),
    "users-edit.steps.1.label": ("HR & Contact", "HR और संपर्क", "HR आणि संपर्क", "HR & Contact"),
    "users-edit.steps.1.caption": (
        "Optional department, designation, employee code, supervisor and desk details.",
        "वैकल्पिक department, designation, employee code, supervisor और desk विवरण।",
        "ऐच्छिक department, designation, employee code, supervisor आणि desk तपशील.",
        "Optional department, designation, employee code, supervisor aur desk details.",
    ),
    "users-edit.steps.2.label": ("Password Reset", "पासवर्ड रीसेट", "पासवर्ड रीसेट", "Password Reset"),
    "users-edit.steps.2.caption": (
        "Leave both fields blank to keep the current password; fill both to force a reset.",
        "current password बनाए रखने के लिए दोनों fields खाली छोड़ें; reset करने के लिए दोनों भरें।",
        "current password कायम ठेवण्यासाठी दोन्ही fields रिकाम्या ठेवा; reset करण्यासाठी दोन्ही भरा.",
        "Current password rakhne ke liye dono fields blank chhodein; reset force karne ke liye dono fill karein.",
    ),
    "users-edit.steps.3.label": ("Save Changes", "बदलाव सहेजें", "बदल जतन करा", "Save Changes"),
    "users-edit.steps.3.caption": (
        "Update User writes the changes and syncs the security context across active sessions.",
        "Update User बदलावों को लिखता है और सभी active sessions में security context को sync करता है।",
        "Update User बदल लिहितो आणि सर्व active sessions मध्ये security context sync करतो.",
        "Update User changes ko save karta hai aur active sessions ke across security context sync karta hai.",
    ),
    "users-edit.fieldRules.0.name": ("User Name", "उपयोगकर्ता नाम", "वापरकर्ता नाव", "User Name"),
    "users-edit.fieldRules.0.description": (
        "Full display name shown across the directory and audit trails.",
        "पूरा display name जो directory और audit trails में दिखाया जाता है।",
        "संपूर्ण display name जो directory आणि audit trails मध्ये दाखवले जाते.",
        "Pura display name jo directory aur audit trails mein dikhta hai.",
    ),
    "users-edit.fieldRules.1.name": ("Email Address", "ईमेल पता", "ईमेल पत्ता", "Email Address"),
    "users-edit.fieldRules.1.description": (
        "Must be a valid, unique email; used for login and notifications.",
        "यह valid और unique email होना चाहिए; login और notifications के लिए उपयोग होता है।",
        "हा valid आणि unique email असणे आवश्यक आहे; login आणि notifications साठी वापरला जातो.",
        "Valid aur unique email hona chahiye; login aur notifications ke liye use hota hai.",
    ),
    "users-edit.fieldRules.2.name": ("Role", "भूमिका", "भूमिका", "Role"),
    "users-edit.fieldRules.2.description": (
        "Determines the permission set applied to this account.",
        "यह तय करता है कि इस account पर कौन-सा permission set लागू होगा।",
        "हे ठरवते की या account वर कोणता permission set लागू होईल.",
        "Ye decide karta hai ki is account par kaunsa permission set apply hoga.",
    ),
    "users-edit.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "users-edit.fieldRules.3.description": (
        "Active/Inactive toggle; deactivating revokes access tokens immediately.",
        "Active/Inactive toggle; deactivate करने पर access tokens तुरंत रद्द हो जाते हैं।",
        "Active/Inactive toggle; deactivate केल्यास access tokens लगेच रद्द होतात.",
        "Active/Inactive toggle; deactivate karne par access tokens turant revoke ho jaate hain.",
    ),
    "users-edit.fieldRules.4.name": ("New Password", "नया पासवर्ड", "नवीन पासवर्ड", "New Password"),
    "users-edit.fieldRules.4.description": (
        "Optional — minimum 8 characters; Confirm New Password must match exactly.",
        "वैकल्पिक — न्यूनतम 8 characters; Confirm New Password बिल्कुल मेल खाना चाहिए।",
        "ऐच्छिक — किमान 8 characters; Confirm New Password अगदी जुळायला हवे.",
        "Optional — minimum 8 characters; Confirm New Password bilkul match hona chahiye.",
    ),
    "users-edit.tip.title": (
        "Deactivation is instant",
        "Deactivation तुरंत होता है",
        "Deactivation तात्काळ होते",
        "Deactivation instant hota hai",
    ),
    "users-edit.tip.body": (
        "Switching Status to Inactive revokes the user's access tokens right away, not at next login — active sessions are cut off immediately.",
        "Status को Inactive में बदलते ही user के access tokens तुरंत रद्द हो जाते हैं, अगले login पर नहीं — active sessions तुरंत बंद हो जाते हैं।",
        "Status Inactive मध्ये बदलताच user चे access tokens लगेच रद्द होतात, पुढील login वेळी नाही — active sessions त्वरित बंद होतात.",
        "Status ko Inactive karte hi user ke access tokens turant revoke ho jaate hain, next login par nahi — active sessions turant cut off ho jaate 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 USERS_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(USERS_EDIT)} users-edit keys.")


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