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

Usage: docker compose exec api python seed_translations_pageinfo_users_create.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_CREATE = {
    "users-create.title": (
        "Create User",
        "उपयोगकर्ता बनाएं",
        "वापरकर्ता तयार करा",
        "Create User",
    ),
    "users-create.subtitle": (
        "Register a new account and grant it a role",
        "एक नया account रजिस्टर करें और उसे एक role प्रदान करें",
        "नवीन account नोंदणी करा आणि त्याला एक role द्या",
        "Naya account register karein aur usse ek role grant karein",
    ),
    "users-create.body.0": (
        "Creates one enterprise user in a single step: profile, credentials, and role are set together, since a role is mandatory to submit.",
        "यह एक ही चरण में एक enterprise user बनाता है: profile, credentials और role एक साथ सेट किए जाते हैं, क्योंकि submit करने के लिए role का होना अनिवार्य है।",
        "हे एकाच टप्प्यात एक enterprise user तयार करते: profile, credentials आणि role एकत्र सेट केले जातात, कारण submit करण्यासाठी role असणे अनिवार्य आहे.",
        "Ye ek hi step mein ek enterprise user create karta hai: profile, credentials, aur role saath mein set hote hain, kyunki submit karne ke liye role hona mandatory hai.",
    ),
    "users-create.body.1": (
        "HR & Contact Details are optional but drive department/org-unit scoped access and reporting once the account is used.",
        "HR और Contact Details वैकल्पिक हैं, लेकिन account उपयोग में आने पर ये department/org-unit आधारित access और reporting तय करते हैं।",
        "HR आणि Contact Details ऐच्छिक आहेत, पण account वापरात आल्यावर ते department/org-unit आधारित access आणि reporting ठरवतात.",
        "HR aur Contact Details optional hain, lekin account use hone par ye department/org-unit scoped access aur reporting decide karte hain.",
    ),
    "users-create.stepsHeading": (
        "What happens on save",
        "Save करने पर क्या होता है",
        "Save केल्यावर काय होते",
        "Save karne par kya hota hai",
    ),
    "users-create.steps.0.label": ("Fill Profile", "Profile भरें", "Profile भरा", "Profile fill karein"),
    "users-create.steps.0.caption": (
        "Name, email, password, role",
        "Name, email, password, role",
        "Name, email, password, role",
        "Name, email, password, role",
    ),
    "users-create.steps.1.label": ("Add HR Details", "HR Details जोड़ें", "HR Details जोडा", "HR Details add karein"),
    "users-create.steps.1.caption": (
        "Optional: dept, supervisor, org unit",
        "वैकल्पिक: dept, supervisor, org unit",
        "ऐच्छिक: dept, supervisor, org unit",
        "Optional: dept, supervisor, org unit",
    ),
    "users-create.steps.2.label": ("Create", "बनाएं", "तयार करा", "Create"),
    "users-create.steps.2.caption": (
        "Account is saved with chosen role",
        "Account चुने गए role के साथ सेव किया जाता है",
        "Account निवडलेल्या role सह सेव्ह केले जाते",
        "Account chosen role ke saath save ho jaata hai",
    ),
    "users-create.steps.3.label": ("Manage Later", "बाद में प्रबंधित करें", "नंतर व्यवस्थापित करा", "Baad mein manage karein"),
    "users-create.steps.3.caption": (
        "Edit or deactivate from Users list",
        "Users list से Edit करें या Deactivate करें",
        "Users list मधून Edit करा किंवा Deactivate करा",
        "Users list se edit ya deactivate karein",
    ),
    "users-create.fieldRules.0.name": ("Role", "Role", "Role", "Role"),
    "users-create.fieldRules.0.description": (
        "Must be an existing backend role — the picker only lists real roles, since an unknown name is rejected at save.",
        "यह एक मौजूदा backend role होना चाहिए — picker केवल वास्तविक roles ही सूचीबद्ध करता है, क्योंकि अज्ञात नाम save के समय reject कर दिया जाता है।",
        "हे एक विद्यमान backend role असणे आवश्यक आहे — picker फक्त खऱ्या roles सूचीबद्ध करतो, कारण अनोळखी नाव save करताना reject केले जाते.",
        "Ye ek existing backend role hona chahiye — picker sirf real roles list karta hai, kyunki unknown naam save karte waqt reject ho jaata hai.",
    ),
    "users-create.fieldRules.1.name": ("Password", "Password", "Password", "Password"),
    "users-create.fieldRules.1.description": (
        "Minimum 8 characters; Confirm Password must match exactly.",
        "न्यूनतम 8 characters; Confirm Password बिल्कुल match होना चाहिए।",
        "किमान 8 characters; Confirm Password तंतोतंत जुळले पाहिजे.",
        "Minimum 8 characters hone chahiye; Confirm Password exactly match karna chahiye.",
    ),
    "users-create.fieldRules.2.name": ("Email Address", "Email Address", "Email Address", "Email Address"),
    "users-create.fieldRules.2.description": (
        "Must be a valid, unique address — used as the login identifier.",
        "यह एक valid और unique address होना चाहिए — इसे login identifier के रूप में उपयोग किया जाता है।",
        "हा एक वैध आणि युनिक address असणे आवश्यक आहे — तो login identifier म्हणून वापरला जातो.",
        "Ye ek valid aur unique address hona chahiye — login identifier ke roop mein use hota hai.",
    ),
    "users-create.fieldRules.3.name": ("Org Unit", "Org Unit", "Org Unit", "Org Unit"),
    "users-create.fieldRules.3.description": (
        "Optional, but scopes what the user can see under org-unit-based permissions.",
        "वैकल्पिक है, लेकिन यह तय करता है कि org-unit-based permissions के अंतर्गत user क्या देख सकता है।",
        "ऐच्छिक आहे, पण org-unit-based permissions अंतर्गत user काय पाहू शकतो हे ते ठरवते.",
        "Optional hai, lekin ye decide karta hai ki org-unit-based permissions ke under user kya dekh sakta hai.",
    ),
    "users-create.fieldRules.4.name": ("Supervisor", "Supervisor", "Supervisor", "Supervisor"),
    "users-create.fieldRules.4.description": (
        "Optional; searches existing users and links reporting hierarchy.",
        "वैकल्पिक; यह मौजूदा users में खोजता है और reporting hierarchy को लिंक करता है।",
        "ऐच्छिक; हे विद्यमान users मध्ये शोधते आणि reporting hierarchy जोडते.",
        "Optional hai; existing users mein search karta hai aur reporting hierarchy link karta hai.",
    ),
    "users-create.tip.title": (
        "Super Admin is powerful",
        "Super Admin शक्तिशाली है",
        "Super Admin शक्तिशाली आहे",
        "Super Admin powerful hai",
    ),
    "users-create.tip.body": (
        "Assigning the Super Admin role grants access to the entire directory, infrastructure, and audit repositories — reserve it for a small, trusted set of accounts.",
        "Super Admin role असाइन करने से पूरे directory, infrastructure, और audit repositories तक access मिल जाता है — इसे केवल कुछ चुनिंदा, भरोसेमंद accounts के लिए सुरक्षित रखें।",
        "Super Admin role असाइन केल्याने संपूर्ण directory, infrastructure, आणि audit repositories चा access मिळतो — तो फक्त काही मोजक्या, विश्वासार्ह accounts साठी राखीव ठेवा.",
        "Super Admin role assign karne se poore directory, infrastructure, aur audit repositories tak access mil jaata hai — ise sirf chunindha, trusted accounts ke chhote se set ke liye reserve 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_CREATE.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_CREATE)} users-create keys.")


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