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

Usage: docker compose exec api python seed_translations_pageinfo_hr_exit_processing.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)
HR_EXIT_PROCESSING = {
    "hr-exit-processing.title": (
        "HR Exit Processing",
        "एचआर एग्ज़िट प्रोसेसिंग",
        "एचआर एग्झिट प्रोसेसिंग",
        "HR Exit Processing",
    ),
    "hr-exit-processing.subtitle": (
        "Release custody when an employee leaves",
        "जब कोई employee छोड़ता है तो custody रिलीज़ करें",
        "जेव्हा एखादा employee सोडतो तेव्हा custody रिलीज करा",
        "Employee jab leave karta hai tab custody release karein",
    ),
    "hr-exit-processing.body.0": (
        "When an employee exits, every asset still checked out to them needs a new custodian. This page runs that hand-off in one step: pick the departing employee and the system orphans all their active custody records, then tries to auto-assign each asset to the head of its org unit as an interim custodian.",
        "जब कोई employee exit करता है, तो उनके पास checked out हर asset को एक नया custodian चाहिए होता है। यह पेज यह hand-off एक ही चरण में करता है: departing employee चुनें और सिस्टम उनके सभी active custody records को orphan कर देता है, फिर हर asset को उसकी org unit के head को interim custodian के रूप में auto-assign करने की कोशिश करता है।",
        "जेव्हा एखादा employee exit करतो, तेव्हा त्याच्याकडे checked out असलेल्या प्रत्येक asset ला नवीन custodian आवश्यक असतो. हे पेज हा hand-off एका टप्प्यात करते: departing employee निवडा आणि सिस्टीम त्यांचे सर्व active custody records orphan करते, त्यानंतर प्रत्येक asset ला त्याच्या org unit च्या head कडे interim custodian म्हणून auto-assign करण्याचा प्रयत्न करते.",
        "Jab koi employee exit karta hai, to unke paas checked-out har asset ko ek naya custodian chahiye hota hai. Ye page ye hand-off ek hi step mein karta hai: departing employee select karein aur system unke saare active custody records ko orphan kar deta hai, phir har asset ko uski org unit ke head ko interim custodian ke roop mein auto-assign karne ki koshish karta hai.",
    ),
    "hr-exit-processing.body.1": (
        "The table below lists every asset currently sitting in 'orphaned' status — including ones where no interim custodian could be found — so compliance can track and close them out.",
        "नीचे दी गई table में फ़िलहाल 'orphaned' status में मौजूद हर asset सूचीबद्ध है — उन assets सहित जिनके लिए कोई interim custodian नहीं मिल सका — ताकि compliance उन्हें track करके close out कर सके।",
        "खालील table मध्ये सध्या 'orphaned' status मध्ये असलेली प्रत्येक asset सूचीबद्ध आहे — ज्यांच्यासाठी कोणताही interim custodian सापडला नाही अशा assets सह — जेणेकरून compliance त्यांचा track ठेवून close out करू शकेल.",
        "Neeche di gayi table mein abhi 'orphaned' status mein padi har asset list hai — un assets samet jinke liye koi interim custodian nahi mil paaya — taaki compliance unhe track karke close out kar sake.",
    ),
    "hr-exit-processing.stepsHeading": (
        "What happens when you process an exit",
        "जब आप exit process करते हैं तो क्या होता है",
        "तुम्ही exit process करता तेव्हा काय होते",
        "Jab aap exit process karte hain to kya hota hai",
    ),
    "hr-exit-processing.steps.0.label": (
        "Select Employee",
        "Employee चुनें",
        "Employee निवडा",
        "Employee select karein",
    ),
    "hr-exit-processing.steps.0.caption": (
        "Search and pick the departing employee.",
        "departing employee को search करके चुनें।",
        "departing employee ला search करून निवडा.",
        "Departing employee ko search karke select karein.",
    ),
    "hr-exit-processing.steps.1.label": (
        "Process Exit",
        "Exit प्रोसेस करें",
        "Exit प्रोसेस करा",
        "Exit process karein",
    ),
    "hr-exit-processing.steps.1.caption": (
        "Submits the exit date and triggers the hand-off.",
        "exit date सबमिट करता है और hand-off को ट्रिगर करता है।",
        "exit date सबमिट करते आणि hand-off ट्रिगर करते.",
        "Exit date submit karta hai aur hand-off trigger karta hai.",
    ),
    "hr-exit-processing.steps.2.label": (
        "Custody Orphaned",
        "Custody Orphaned",
        "Custody Orphaned",
        "Custody Orphaned",
    ),
    "hr-exit-processing.steps.2.caption": (
        "All their active/pending custody records flip to 'orphaned'.",
        "उनके सभी active/pending custody records 'orphaned' में बदल जाते हैं।",
        "त्यांचे सर्व active/pending custody records 'orphaned' मध्ये बदलतात.",
        "Unke saare active/pending custody records 'orphaned' mein badal jaate hain.",
    ),
    "hr-exit-processing.steps.3.label": (
        "Interim Assigned",
        "Interim Assigned",
        "Interim Assigned",
        "Interim Assigned",
    ),
    "hr-exit-processing.steps.3.caption": (
        "Asset's OU head gets a new pending-acceptance custody, if one exists.",
        "यदि कोई मौजूद हो, तो asset की OU head को नई pending-acceptance custody मिलती है।",
        "जर एखादा अस्तित्वात असेल, तर asset च्या OU head ला नवीन pending-acceptance custody मिळते.",
        "Agar koi exist karta hai, to asset ke OU head ko nayi pending-acceptance custody milti hai.",
    ),
    "hr-exit-processing.fieldRules.0.name": (
        "Departing Employee",
        "जाने वाला Employee",
        "जाणारा Employee",
        "Departing Employee",
    ),
    "hr-exit-processing.fieldRules.0.description": (
        "Searchable user picker; determines which custody records get orphaned.",
        "Searchable user picker; तय करता है कि कौन-से custody records orphan होंगे।",
        "Searchable user picker; कोणते custody records orphan होतील हे ठरवते.",
        "Searchable user picker; decide karta hai ki kaunse custody records orphan honge.",
    ),
    "hr-exit-processing.fieldRules.1.name": (
        "Exit Date",
        "एग्ज़िट तिथि",
        "एग्झिट तारीख",
        "Exit Date",
    ),
    "hr-exit-processing.fieldRules.1.description": (
        "Defaults to today; becomes the effective-from date on the new interim custody record.",
        "डिफ़ॉल्ट रूप से आज की तारीख; यह नए interim custody record पर effective-from date बन जाती है।",
        "डीफॉल्टनुसार आजची तारीख; ही नवीन interim custody record वर effective-from date बनते.",
        "Default aaj ki date hoti hai; ye naye interim custody record par effective-from date ban jaati hai.",
    ),
    "hr-exit-processing.fieldRules.2.name": (
        "Asset",
        "Asset",
        "Asset",
        "Asset",
    ),
    "hr-exit-processing.fieldRules.2.description": (
        "Name and reference code of the orphaned asset.",
        "orphaned asset का नाम और reference code।",
        "orphaned asset चे नाव आणि reference code.",
        "Orphaned asset ka naam aur reference code.",
    ),
    "hr-exit-processing.fieldRules.3.name": (
        "Last Custodian",
        "अंतिम Custodian",
        "शेवटचा Custodian",
        "Last Custodian",
    ),
    "hr-exit-processing.fieldRules.3.description": (
        "User ID of whoever last held custody before it was orphaned.",
        "orphan होने से पहले custody रखने वाले अंतिम व्यक्ति की User ID।",
        "orphan होण्यापूर्वी custody ज्याच्याकडे होती त्या शेवटच्या व्यक्तीचा User ID.",
        "Orphan hone se pehle jiske paas custody thi uski User ID.",
    ),
    "hr-exit-processing.fieldRules.4.name": (
        "Since",
        "कब से",
        "कधीपासून",
        "Since",
    ),
    "hr-exit-processing.fieldRules.4.description": (
        "Date the custody record entered orphaned status.",
        "वह तारीख जब custody record 'orphaned' status में गया।",
        "ती तारीख जेव्हा custody record 'orphaned' status मध्ये गेला.",
        "Wo date jab custody record 'orphaned' status mein gaya.",
    ),
    "hr-exit-processing.tip.title": (
        "A gap between Orphaned and Interim Assigned is expected",
        "Orphaned और Interim Assigned के बीच अंतर होना सामान्य है",
        "Orphaned आणि Interim Assigned मध्ये फरक असणे अपेक्षित आहे",
        "Orphaned aur Interim Assigned ke beech gap hona normal hai",
    ),
    "hr-exit-processing.tip.body": (
        "Interim assignment only succeeds if the asset's org unit has a designated head who isn't the departing employee. If not, the asset stays orphaned with no replacement custodian — 'Failed' only counts data errors, not missing OU heads — so check the Orphaned Assets table after every exit and reassign those manually via Custody Transfer.",
        "Interim assignment तभी सफल होता है जब asset की org unit का कोई designated head हो, जो departing employee न हो। अगर ऐसा नहीं है, तो asset बिना किसी replacement custodian के orphaned ही रहता है — 'Failed' केवल data errors गिनता है, missing OU heads को नहीं — इसलिए हर exit के बाद Orphaned Assets table ज़रूर देखें और उन्हें Custody Transfer के ज़रिए मैन्युअल रूप से reassign करें।",
        "Interim assignment तेव्हाच यशस्वी होते जेव्हा asset च्या org unit ला एक designated head असतो, जो departing employee नसतो. जर असे नसेल, तर asset कोणत्याही replacement custodian शिवाय orphaned च राहते — 'Failed' फक्त data errors मोजते, missing OU heads नाही — म्हणून प्रत्येक exit नंतर Orphaned Assets table तपासा आणि त्यांना Custody Transfer द्वारे manually reassign करा.",
        "Interim assignment tabhi successful hota hai jab asset ki org unit ka koi designated head ho, jo departing employee na ho. Agar aisa nahi hai, to asset bina kisi replacement custodian ke orphaned hi rehta hai — 'Failed' sirf data errors count karta hai, missing OU heads nahi — isliye har exit ke baad Orphaned Assets table zaroor check karein aur unhe Custody Transfer se manually reassign 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 HR_EXIT_PROCESSING.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(HR_EXIT_PROCESSING)} hr-exit-processing keys.")


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