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

Usage: docker compose exec api python seed_translations_pageinfo_users.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 = {
    "users.title": (
        "User Management",
        "उपयोगकर्ता प्रबंधन",
        "वापरकर्ता व्यवस्थापन",
        "User Management",
    ),
    "users.subtitle": (
        "Create, view and manage every login in the system",
        "सिस्टम के हर लॉगिन को बनाएं, देखें और प्रबंधित करें",
        "सिस्टममधील प्रत्येक लॉगिन तयार करा, पहा आणि व्यवस्थापित करा",
        "System ke har login ko create, view aur manage karein",
    ),
    "users.body.0": (
        "Every person who signs in to AAMS is a user record here — their login, role and HR/contact details.",
        "AAMS में साइन इन करने वाला हर व्यक्ति यहाँ एक user record है — उनकी login, role और HR/contact details यहीं मौजूद हैं।",
        "AAMS मध्ये साइन इन करणारी प्रत्येक व्यक्ती येथे एक user record आहे — त्यांचे login, role आणि HR/contact details येथे असतात.",
        "AAMS mein sign in karne wala har person yahan ek user record hota hai — unki login, role aur HR/contact details yahin hoti hain.",
    ),
    "users.body.1": (
        "Role assignment is what actually grants permissions: deactivating a user blocks their login without deleting their history, so prefer Deactivate over Delete when someone leaves.",
        "Role असाइनमेंट ही असल में permissions देता है: किसी user को deactivate करने पर उसकी history डिलीट किए बिना उसका login रुक जाता है, इसलिए जब कोई व्यक्ति संगठन छोड़े तो Delete के बजाय Deactivate को प्राथमिकता दें।",
        "Role असाइनमेंट हीच खरं तर permissions देते: एखाद्या user ला deactivate केल्यास त्याचा history न हटवता त्याचे login थांबते, त्यामुळे कोणी संस्था सोडल्यावर Delete ऐवजी Deactivate ला प्राधान्य द्या.",
        "Role assignment hi actually permissions deta hai: kisi user ko deactivate karne se unki history delete kiye bina unka login block ho jaata hai, isliye jab koi leave kare to Delete ki jagah Deactivate ko prefer karein.",
    ),
    "users.stepsHeading": (
        "Typical lifecycle",
        "सामान्य lifecycle",
        "ठराविक lifecycle",
        "Typical lifecycle",
    ),
    "users.steps.0.label": ("Create", "बनाएं", "तयार करा", "Create"),
    "users.steps.0.caption": (
        "Set name, email, password and role in the create form.",
        "Create फ़ॉर्म में name, email, password और role सेट करें।",
        "Create फॉर्ममध्ये name, email, password आणि role सेट करा.",
        "Create form mein name, email, password aur role set karein.",
    ),
    "users.steps.1.label": ("Assign role", "Role असाइन करें", "Role असाइन करा", "Role assign karein"),
    "users.steps.1.caption": (
        "Role drives every permission the user has — assign it carefully.",
        "Role ही user के पास मौजूद हर permission तय करता है — इसे सावधानी से असाइन करें।",
        "Role हाच user कडे असलेली प्रत्येक permission ठरवतो — तो काळजीपूर्वक असाइन करा.",
        "Role hi decide karta hai ki user ke paas kaunsi permission hai — ise carefully assign karein.",
    ),
    "users.steps.2.label": ("Active", "सक्रिय", "सक्रिय", "Active"),
    "users.steps.2.caption": (
        "User can log in and use the system per their role.",
        "User अपने role के अनुसार login करके सिस्टम का उपयोग कर सकता है।",
        "User त्याच्या role नुसार login करून सिस्टम वापरू शकतो.",
        "User apne role ke hisaab se login karke system use kar sakta hai.",
    ),
    "users.steps.3.label": ("Deactivate", "निष्क्रिय करें", "निष्क्रिय करा", "Deactivate"),
    "users.steps.3.caption": (
        "Blocks login instantly; record and audit history are kept.",
        "Login को तुरंत ब्लॉक कर देता है; record और audit history सुरक्षित रहते हैं।",
        "Login लगेच ब्लॉक होते; record आणि audit history जतन केली जाते.",
        "Login turant block ho jaata hai; record aur audit history safe rehti hai.",
    ),
    "users.fieldRules.0.name": (
        "User Name / Email",
        "User Name / Email",
        "User Name / Email",
        "User Name / Email",
    ),
    "users.fieldRules.0.description": (
        "Email must be a valid address and is used as the login identifier.",
        "Email एक valid address होना चाहिए और इसे login identifier के रूप में उपयोग किया जाता है।",
        "Email वैध address असणे आवश्यक आहे आणि तो login identifier म्हणून वापरला जातो.",
        "Email ek valid address hona chahiye aur ye login identifier ke roop mein use hota hai.",
    ),
    "users.fieldRules.1.name": (
        "Password / Confirm Password",
        "Password / Confirm Password",
        "Password / Confirm Password",
        "Password / Confirm Password",
    ),
    "users.fieldRules.1.description": (
        "Minimum 8 characters; both fields must match exactly.",
        "न्यूनतम 8 characters; दोनों fields बिल्कुल match होने चाहिए।",
        "किमान 8 characters; दोन्ही fields तंतोतंत जुळल्या पाहिजेत.",
        "Minimum 8 characters hone chahiye; dono fields exactly match karne chahiye.",
    ),
    "users.fieldRules.2.name": ("Role", "Role", "Role", "Role"),
    "users.fieldRules.2.description": (
        "Determines every permission the user has across the system.",
        "यह पूरे सिस्टम में user के पास मौजूद हर permission तय करता है।",
        "हे संपूर्ण सिस्टममध्ये user कडे असलेली प्रत्येक permission ठरवते.",
        "Ye pure system mein user ke paas kaunsi permission hai wo decide karta hai.",
    ),
    "users.fieldRules.3.name": (
        "Department / Org Unit / Designation",
        "Department / Org Unit / Designation",
        "Department / Org Unit / Designation",
        "Department / Org Unit / Designation",
    ),
    "users.fieldRules.3.description": (
        "Optional HR metadata used for reporting and scoping, not access control.",
        "यह वैकल्पिक HR metadata है जो reporting और scoping के लिए उपयोग होता है, access control के लिए नहीं।",
        "हे ऐच्छिक HR metadata आहे जे reporting आणि scoping साठी वापरले जाते, access control साठी नाही.",
        "Ye optional HR metadata hai jo reporting aur scoping ke liye use hota hai, access control ke liye nahi.",
    ),
    "users.tip.title": (
        "Deactivate, don't delete",
        "Deactivate करें, Delete नहीं",
        "Deactivate करा, Delete नको",
        "Deactivate karo, Delete mat karo",
    ),
    "users.tip.body": (
        "Delete permanently removes the user; Deactivate (the status toggle in the row actions) instantly blocks login while preserving audit history — use it for offboarding.",
        "Delete user को permanently हटा देता है; Deactivate (row actions में मौजूद status toggle) audit history को सुरक्षित रखते हुए login को तुरंत ब्लॉक कर देता है — offboarding के लिए इसका उपयोग करें।",
        "Delete user कायमचा काढून टाकतो; Deactivate (row actions मधील status toggle) audit history जतन करत login लगेच ब्लॉक करतो — offboarding साठी हे वापरा.",
        "Delete user ko permanently remove kar deta hai; Deactivate (row actions mein status toggle) audit history preserve karte hue login ko turant block kar deta hai — offboarding ke liye isse use karein.",
    ),
}


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.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)} users keys.")


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