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

Usage: docker compose exec api python seed_translations_pageinfo_org_units_assign.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_ASSIGN = {
    "org-units-assign.title": (
        "Approval Delegation Matrix",
        "अनुमोदन प्रत्यायोजन मैट्रिक्स",
        "मंजुरी प्रत्यायोजन मॅट्रिक्स",
        "Approval Delegation Matrix",
    ),
    "org-units-assign.subtitle": (
        "Grant a role the authority to approve, within one org unit",
        "किसी role को एक org unit के भीतर अनुमोदन (approve) करने का अधिकार प्रदान करें",
        "एका org unit च्या आत मंजुरी देण्याचा अधिकार एखाद्या role ला प्रदान करा",
        "Ek role ko ek org unit ke andar approve karne ka authority grant karein",
    ),
    "org-units-assign.body.0": (
        "This creates a delegation-matrix entry: it lets everyone holding a given role approve records for a given module (or all modules) inside one org unit, optionally capped at a maximum amount. It is role-based, not person-based — there is no \"manager of this unit\" field, and picking a role hands the authority to everyone who currently holds it, present and future.",
        "यह एक delegation-matrix entry बनाता है: यह किसी दिए गए role को रखने वाले हर व्यक्ति को एक org unit के भीतर किसी दिए गए module (या सभी modules) के records अनुमोदित करने देता है, वैकल्पिक रूप से अधिकतम राशि तक सीमित। यह role-based है, person-based नहीं — यहाँ कोई \"इस unit का manager\" फ़ील्ड नहीं है, और कोई role चुनने से यह अधिकार उसे रखने वाले हर व्यक्ति को मिल जाता है, वर्तमान और भविष्य दोनों में।",
        "हे एक delegation-matrix entry तयार करते: हे दिलेला role असलेल्या प्रत्येकाला एका org unit च्या आत दिलेल्या module (किंवा सर्व modules) च्या records ला मंजुरी देण्याची परवानगी देते, ऐच्छिकरित्या कमाल रकमेपर्यंत मर्यादित. हे role-based आहे, person-based नाही — येथे \"या unit चा manager\" असे कोणतेही फील्ड नाही, आणि एखादा role निवडल्याने तो अधिकार सध्या आणि भविष्यात तो role धारण करणाऱ्या प्रत्येकाला मिळतो.",
        "Ye ek delegation-matrix entry create karta hai: isse jo bhi ek given role hold karta hai wo ek org unit ke andar ek given module (ya sabhi modules) ke records approve kar sakta hai, optionally ek maximum amount tak capped. Ye role-based hai, person-based nahi — yahan koi \"is unit ka manager\" field nahi hai, aur ek role select karne se wo authority us role ko hold karne wale har kisi ko mil jaati hai, present aur future dono mein.",
    ),
    "org-units-assign.body.1": (
        "Selecting an org unit shows any delegations that already exist for it, so you can check for overlaps or gaps before adding another one.",
        "किसी org unit को चुनने पर उसके लिए पहले से मौजूद सभी delegations दिखाई देते हैं, ताकि आप एक और जोड़ने से पहले overlaps या gaps जाँच सकें।",
        "एखादी org unit निवडल्यास तिच्यासाठी आधीपासून अस्तित्वात असलेले सर्व delegations दिसतात, जेणेकरून तुम्ही आणखी एक जोडण्यापूर्वी overlaps किंवा gaps तपासू शकाल.",
        "Ek org unit select karne par uske liye already exist karne wale sabhi delegations dikhte hain, taaki aap ek aur add karne se pehle overlaps ya gaps check kar sakein.",
    ),
    "org-units-assign.stepsHeading": (
        "How a delegation entry is built",
        "एक delegation entry कैसे बनती है",
        "एक delegation entry कशी तयार होते",
        "Ek delegation entry kaise banti hai",
    ),
    "org-units-assign.steps.0.label": ("Pick Org Unit", "Org Unit चुनें", "Org Unit निवडा", "Org Unit Pick Karein"),
    "org-units-assign.steps.0.caption": (
        "Existing delegations for it load automatically.",
        "इसके लिए मौजूदा delegations अपने आप लोड हो जाते हैं।",
        "यासाठी विद्यमान delegations आपोआप लोड होतात.",
        "Iske existing delegations automatically load ho jaate hain.",
    ),
    "org-units-assign.steps.1.label": ("Role + Scope", "Role + Scope", "Role + Scope", "Role + Scope"),
    "org-units-assign.steps.1.caption": (
        "Which role, and which module (or \"all\") it can approve.",
        "कौन सा role, और यह किस module (या \"all\") को अनुमोदित कर सकता है।",
        "कोणता role, आणि तो कोणत्या module (किंवा \"all\") ला मंजुरी देऊ शकतो.",
        "Kaunsa role, aur ye kaunsa module (ya \"all\") approve kar sakta hai.",
    ),
    "org-units-assign.steps.2.label": ("Set Limit", "सीमा सेट करें", "मर्यादा सेट करा", "Limit Set Karein"),
    "org-units-assign.steps.2.caption": (
        "Optional max approval amount — blank means unlimited.",
        "वैकल्पिक अधिकतम approval राशि — खाली छोड़ने का मतलब असीमित है।",
        "ऐच्छिक कमाल approval रक्कम — रिकामे ठेवल्यास अमर्यादित.",
        "Optional maximum approval amount — blank rakhne ka matlab unlimited hai.",
    ),
    "org-units-assign.steps.3.label": ("Create", "बनाएं", "तयार करा", "Create Karein"),
    "org-units-assign.steps.3.caption": (
        "Takes effect from the chosen date; you return to Org Units.",
        "यह चुनी गई तारीख से प्रभावी होता है; आप Org Units पर वापस लौट जाते हैं।",
        "हे निवडलेल्या तारखेपासून लागू होते; तुम्ही Org Units वर परत जाता.",
        "Ye chuni gayi date se effective hota hai; aap wapas Org Units par chale jaate hain.",
    ),
    "org-units-assign.fieldRules.0.name": ("Org Unit", "Org Unit", "Org Unit", "Org Unit"),
    "org-units-assign.fieldRules.0.description": (
        "The org unit this delegation applies to; also filters the existing-delegations list shown below it.",
        "वह org unit जिस पर यह delegation लागू होता है; यह नीचे दिखाई गई existing-delegations सूची को भी फ़िल्टर करता है।",
        "हे delegation ज्या org unit ला लागू होते; हे खाली दाखवलेल्या existing-delegations यादीलाही फिल्टर करते.",
        "Wo org unit jispar ye delegation apply hota hai; ye niche dikhayi gayi existing-delegations list ko bhi filter karta hai.",
    ),
    "org-units-assign.fieldRules.1.name": ("Role", "Role", "Role", "Role"),
    "org-units-assign.fieldRules.1.description": (
        "Any user holding this role gets the authority — matched by role name, not a fixed role code.",
        "इस role को रखने वाला कोई भी user यह अधिकार पाता है — इसका मिलान role के नाम से होता है, किसी fixed role code से नहीं।",
        "हा role असलेल्या कोणत्याही user ला हा अधिकार मिळतो — हे role च्या नावाने जुळवले जाते, कोणत्याही fixed role code ने नाही.",
        "Ye role hold karne wala koi bhi user ye authority paata hai — ye role name se match hota hai, kisi fixed role code se nahi.",
    ),
    "org-units-assign.fieldRules.2.name": ("Delegation Scope", "Delegation Scope", "Delegation Scope", "Delegation Scope"),
    "org-units-assign.fieldRules.2.description": (
        "Limits approval to one module's workflow templates, or choose \"All modules\" for every module.",
        "यह अनुमोदन को एक module के workflow templates तक सीमित करता है, या हर module के लिए \"All modules\" चुनें।",
        "हे मंजुरी एका module च्या workflow templates पुरती मर्यादित करते, किंवा प्रत्येक module साठी \"All modules\" निवडा.",
        "Ye approval ko ek module ke workflow templates tak limit karta hai, ya har module ke liye \"All modules\" choose karein.",
    ),
    "org-units-assign.fieldRules.3.name": ("Max Approval Amount", "अधिकतम Approval राशि", "कमाल Approval रक्कम", "Max Approval Amount"),
    "org-units-assign.fieldRules.3.description": (
        "Caps what this role can approve in money terms; leave blank for no cap.",
        "यह तय करता है कि यह role money के मामले में अधिकतम कितना अनुमोदित कर सकता है; कोई सीमा न रखने के लिए खाली छोड़ें।",
        "हे role money च्या दृष्टीने जास्तीत जास्त किती मंजूर करू शकतो हे मर्यादित करते; मर्यादा नको असल्यास रिकामे ठेवा.",
        "Ye cap karta hai ki ye role money terms mein maximum kitna approve kar sakta hai; koi cap nahi chahiye to blank rakhein.",
    ),
    "org-units-assign.fieldRules.4.name": ("Remarks", "टिप्पणी (Remarks)", "शेरा (Remarks)", "Remarks"),
    "org-units-assign.fieldRules.4.description": (
        "Local note only — it is not sent to the backend or saved with the entry.",
        "केवल local note — यह backend को नहीं भेजा जाता और न ही entry के साथ save होता है।",
        "फक्त local note — हे backend ला पाठवले जात नाही किंवा entry सोबत save होत नाही.",
        "Sirf local note hai — ye backend ko send nahi hota aur na hi entry ke saath save hota hai.",
    ),
    "org-units-assign.tip.title": (
        "Remarks are never saved",
        "Remarks कभी save नहीं होते",
        "Remarks कधीही save होत नाहीत",
        "Remarks kabhi save nahi hote",
    ),
    "org-units-assign.tip.body": (
        "The Remarks box is not persisted — it exists only to help you think through the rationale while filling the form. Record the actual justification elsewhere if you need an audit trail.",
        "Remarks box persist नहीं होता — यह केवल इसलिए है ताकि फ़ॉर्म भरते समय आप rationale पर विचार कर सकें। यदि आपको audit trail चाहिए तो वास्तविक justification कहीं और दर्ज करें।",
        "Remarks box persist होत नाही — फॉर्म भरताना rationale विचार करण्यास मदत व्हावी म्हणून हे फक्त अस्तित्वात आहे. audit trail हवा असल्यास प्रत्यक्ष justification इतरत्र नोंदवा.",
        "Remarks box persist nahi hota — ye sirf isliye hai taaki form fill karte waqt aap rationale soch sakein. Agar aapko audit trail chahiye to actual justification kahin aur record 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 ORG_UNITS_ASSIGN.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_ASSIGN)} org-units-assign keys.")


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