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

Usage: docker compose exec api python seed_translations_pageinfo_org_units_add.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)
ORG_UNITS_ADD = {
    "org-units-add.title": (
        "Add New Organisation Unit",
        "नई Organisation Unit जोड़ें",
        "नवीन Organisation Unit जोडा",
        "Naya Organisation Unit add karein",
    ),
    "org-units-add.subtitle": (
        "Create a node in your organisation tree",
        "अपने organisation tree में एक नोड बनाएं",
        "तुमच्या organisation tree मध्ये एक नोड तयार करा",
        "Apne organisation tree mein ek node create karein",
    ),
    "org-units-add.body.0": (
        "Create a new department, division, or other organisational unit and place it in the hierarchy.",
        "एक नया department, division, या अन्य organisational unit बनाएं और इसे hierarchy में रखें।",
        "नवीन department, division, किंवा इतर organisational unit तयार करा आणि ती hierarchy मध्ये ठेवा.",
        "Ek naya department, division, ya koi aur organisational unit create karein aur use hierarchy mein place karein.",
    ),
    "org-units-add.body.1": (
        "Client Type (Enterprise vs Government) decides which Org Unit Type list you get — e.g. Division/Business Unit vs Ministry/Directorate — and switching it resets the type you've picked. The unit is created pending approval; it only becomes usable once approved in the Approval Queue.",
        "Client Type (Enterprise बनाम Government) यह तय करता है कि आपको कौन-सी Org Unit Type लिस्ट मिलेगी — जैसे Division/Business Unit बनाम Ministry/Directorate — और इसे बदलने पर आपके द्वारा चुना गया type रीसेट हो जाता है। यह unit pending approval की स्थिति में बनाई जाती है; यह Approval Queue में approve होने के बाद ही उपयोग करने योग्य बनती है।",
        "Client Type (Enterprise विरुद्ध Government) हे ठरवते की तुम्हाला कोणती Org Unit Type यादी मिळेल — उदा. Division/Business Unit विरुद्ध Ministry/Directorate — आणि तो बदलल्यास तुम्ही निवडलेला type रीसेट होतो. ही unit pending approval स्थितीत तयार होते; ती Approval Queue मध्ये approve झाल्यावरच वापरण्यायोग्य बनते.",
        "Client Type (Enterprise vs Government) decide karta hai ki aapko kaunsi Org Unit Type list milegi — jaise Division/Business Unit vs Ministry/Directorate — aur ise switch karne par aapka chuna hua type reset ho jaata hai. Unit pending approval status mein create hoti hai; ye sirf Approval Queue mein approve hone ke baad hi usable banti hai.",
    ),
    "org-units-add.stepsHeading": (
        "How a new unit is created",
        "नई unit कैसे बनाई जाती है",
        "नवीन unit कशी तयार केली जाते",
        "Nayi unit kaise create hoti hai",
    ),
    "org-units-add.steps.0.label": (
        "Pick Client Type",
        "Client Type चुनें",
        "Client Type निवडा",
        "Client Type select karein",
    ),
    "org-units-add.steps.0.caption": (
        "Enterprise or Government — controls the Org Unit Type options below.",
        "Enterprise या Government — नीचे दिए गए Org Unit Type विकल्पों को नियंत्रित करता है।",
        "Enterprise किंवा Government — खालील Org Unit Type पर्याय नियंत्रित करते.",
        "Enterprise ya Government — neeche ke Org Unit Type options ko control karta hai.",
    ),
    "org-units-add.steps.1.label": (
        "Choose Type & Parent",
        "Type और Parent चुनें",
        "Type आणि Parent निवडा",
        "Type aur Parent choose karein",
    ),
    "org-units-add.steps.1.caption": (
        "Org Unit Type plus an optional Parent Unit to place it in the tree.",
        "Org Unit Type के साथ एक वैकल्पिक Parent Unit, ताकि इसे tree में रखा जा सके।",
        "Org Unit Type सोबत एक ऐच्छिक Parent Unit, जेणेकरून ती tree मध्ये ठेवता येईल.",
        "Org Unit Type ke saath ek optional Parent Unit, taaki ise tree mein place kiya ja sake.",
    ),
    "org-units-add.steps.2.label": (
        "Add legal/governance details",
        "Legal/governance विवरण जोड़ें",
        "Legal/governance तपशील जोडा",
        "Legal/governance details add karein",
    ),
    "org-units-add.steps.2.caption": (
        "Optional: CIN/PAN/GSTIN, legal-entity and SEBI-listed flags.",
        "वैकल्पिक: CIN/PAN/GSTIN, legal-entity और SEBI-listed फ़्लैग।",
        "ऐच्छिक: CIN/PAN/GSTIN, legal-entity आणि SEBI-listed फ्लॅग्ज.",
        "Optional: CIN/PAN/GSTIN, legal-entity aur SEBI-listed flags.",
    ),
    "org-units-add.steps.3.label": (
        "Submit for approval",
        "Approval के लिए सबमिट करें",
        "Approval साठी सबमिट करा",
        "Approval ke liye submit karein",
    ),
    "org-units-add.steps.3.caption": (
        "Unit is created but stays inactive until approved in the Approval Queue.",
        "Unit बन जाती है, लेकिन Approval Queue में approve होने तक inactive बनी रहती है।",
        "Unit तयार होते, पण Approval Queue मध्ये approve होईपर्यंत inactive राहते.",
        "Unit create ho jaati hai, lekin Approval Queue mein approve hone tak inactive rehti hai.",
    ),
    "org-units-add.fieldRules.0.name": (
        "Unit Name",
        "यूनिट नाम",
        "युनिट नाव",
        "Unit Name",
    ),
    "org-units-add.fieldRules.0.description": (
        "Display name for the unit, e.g. \"Finance Department\".",
        "unit के लिए display नाम, जैसे \"Finance Department\"।",
        "unit साठी display नाव, उदा. \"Finance Department\".",
        "Unit ke liye display name, jaise \"Finance Department\".",
    ),
    "org-units-add.fieldRules.1.name": (
        "Client Type",
        "क्लाइंट टाइप",
        "क्लायंट टाईप",
        "Client Type",
    ),
    "org-units-add.fieldRules.1.description": (
        "Loaded from Client Type Masters; its code selects the Enterprise or Government Org Unit Type list.",
        "Client Type Masters से लोड होता है; इसका code Enterprise या Government Org Unit Type लिस्ट को चुनता है।",
        "Client Type Masters मधून लोड होते; त्याचा code Enterprise किंवा Government Org Unit Type यादी निवडतो.",
        "Client Type Masters se load hota hai; iska code Enterprise ya Government Org Unit Type list select karta hai.",
    ),
    "org-units-add.fieldRules.2.name": (
        "Org Unit Type",
        "ऑर्ग यूनिट टाइप",
        "ऑर्ग युनिट टाईप",
        "Org Unit Type",
    ),
    "org-units-add.fieldRules.2.description": (
        "Structural role (Division, Ministry, CPSE, ...); picking \"CPSE\" reveals an extra CPSE Details card.",
        "Structural role (Division, Ministry, CPSE, ...); \"CPSE\" चुनने पर एक अतिरिक्त CPSE Details card दिखाई देता है।",
        "Structural role (Division, Ministry, CPSE, ...); \"CPSE\" निवडल्यास एक अतिरिक्त CPSE Details card दिसते.",
        "Structural role (Division, Ministry, CPSE, ...); \"CPSE\" select karne par ek extra CPSE Details card dikhta hai.",
    ),
    "org-units-add.fieldRules.3.name": (
        "Parent Unit",
        "पैरेंट यूनिट",
        "पॅरेंट युनिट",
        "Parent Unit",
    ),
    "org-units-add.fieldRules.3.description": (
        "Leave unset to create a root unit; otherwise nests this unit under an existing one.",
        "root unit बनाने के लिए इसे खाली छोड़ दें; अन्यथा यह unit किसी मौजूदा unit के अंदर nest हो जाएगी।",
        "root unit तयार करण्यासाठी हे रिकामे ठेवा; अन्यथा ही unit एखाद्या existing unit च्या आत nest होते.",
        "Root unit banane ke liye ise unset chhod dein; warna ye unit kisi existing unit ke andar nest ho jaayegi.",
    ),
    "org-units-add.fieldRules.4.name": (
        "Legal Entity / SEBI Listed",
        "लीगल एंटिटी / SEBI-लिस्टेड",
        "लीगल एंटिटी / SEBI-लिस्टेड",
        "Legal Entity / SEBI Listed",
    ),
    "org-units-add.fieldRules.4.description": (
        "Toggling Legal Entity on reveals Registered Office and RoC Jurisdiction fields.",
        "Legal Entity को on करने पर Registered Office और RoC Jurisdiction फ़ील्ड दिखाई देती हैं।",
        "Legal Entity on केल्यास Registered Office आणि RoC Jurisdiction फील्ड्स दिसतात.",
        "Legal Entity ko on karne par Registered Office aur RoC Jurisdiction fields dikhti hain.",
    ),
    "org-units-add.tip.title": (
        "Pending approval, not live",
        "Pending approval, अभी live नहीं",
        "Pending approval, अजून live नाही",
        "Pending approval, abhi live nahi",
    ),
    "org-units-add.tip.body": (
        "Submitting doesn't make the unit usable immediately — it's created in a pending state and someone else must approve it in the Approval Queue before users can be assigned to it or assets scoped to it.",
        "Submit करने से unit तुरंत उपयोग करने योग्य नहीं बन जाती — यह pending स्थिति में बनती है और किसी और को इसे Approval Queue में approve करना होगा, तभी users को इसमें assign किया जा सकेगा या assets को इसके दायरे में scope किया जा सकेगा।",
        "Submit केल्याने unit लगेच वापरण्यायोग्य होत नाही — ती pending स्थितीत तयार होते आणि दुसऱ्या कोणाला तरी Approval Queue मध्ये ती approve करावी लागते, त्यानंतरच users ला त्यात assign करता येते किंवा assets ला त्याच्या scope मध्ये ठेवता येते.",
        "Submit karne se unit turant usable nahi ho jaati — ye pending state mein create hoti hai aur kisi aur ko Approval Queue mein ise approve karna hota hai, tabhi users ko isse assign kiya ja sakta hai ya assets ko iske scope mein rakha ja sakta hai.",
    ),
}


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 ORG_UNITS_ADD.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(ORG_UNITS_ADD)} org-units-add keys.")


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