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

Usage: docker compose exec api python seed_translations_pageinfo_custody_liability_report.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)
CUSTODY_LIABILITY_REPORT = {
    "custody-liability-report.title": (
        "Assets in a Person's Care",
        "किसी व्यक्ति की देखरेख में मौजूद Assets",
        "एखाद्या व्यक्तीच्या देखरेखीखालील Assets",
        "Ek person ke paas custody mein jo Assets hain",
    ),
    "custody-liability-report.subtitle": (
        "What one person is financially answerable for right now",
        "अभी कोई व्यक्ति वित्तीय रूप से किसके लिए जवाबदेह है",
        "सध्या एखादी व्यक्ती आर्थिकदृष्ट्या कशासाठी जबाबदार आहे",
        "Abhi ek person financially kis cheez ke liye jawabdeh hai",
    ),
    "custody-liability-report.body.0": (
        "Lists every asset currently assigned to one person, with the original purchase price next to today's depreciated value — the amount they're effectively liable for if an item is lost or damaged.",
        "किसी एक व्यक्ति को वर्तमान में assign किए गए हर asset को सूचीबद्ध करता है, साथ ही मूल purchase price को आज की depreciated value के बगल में दिखाता है — यह वह राशि है जिसके लिए वे प्रभावी रूप से उत्तरदायी हैं यदि कोई item खो जाता है या क्षतिग्रस्त हो जाता है।",
        "सध्या एका व्यक्तीला assign केलेल्या प्रत्येक asset ची यादी देते, मूळ purchase price आजच्या depreciated value च्या शेजारी दाखवते — जर एखादी item हरवली किंवा खराब झाली तर ती व्यक्ती प्रत्यक्षात ज्या रकमेसाठी जबाबदार आहे.",
        "Ek person ko abhi jo bhi assets assign hain unki poori list deti hai, original purchase price ko aaj ki depreciated value ke saath side-by-side dikhati hai — ye wahi amount hai jiske liye woh effectively liable hai agar item lost ya damage ho jaaye.",
    ),
    "custody-liability-report.body.1": (
        "You can only pull your own report unless you hold a manager/admin permission (custody:read_any) — the person picker only appears for those roles; everyone else sees their own name, fixed.",
        "जब तक आपके पास manager/admin permission (custody:read_any) न हो, आप केवल अपनी खुद की report ही देख सकते हैं — person picker केवल इन roles के लिए दिखाई देता है; बाकी सभी को अपना ही नाम, स्थिर रूप से, दिखता है।",
        "जोपर्यंत तुमच्याकडे manager/admin permission (custody:read_any) नाही, तोपर्यंत तुम्ही फक्त तुमचाच report पाहू शकता — person picker फक्त त्या roles साठीच दिसतो; बाकी सर्वांना त्यांचे स्वतःचे नाव, निश्चित स्वरूपात, दिसते.",
        "Aap sirf apni khud ki report tabhi dekh sakte hain jab tak aapke paas manager/admin permission (custody:read_any) na ho — person picker sirf un roles ke liye dikhta hai; baaki sabko apna hi naam, fixed, dikhta hai.",
    ),
    "custody-liability-report.stepsHeading": (
        "How the report is built",
        "Report कैसे तैयार होती है",
        "Report कशी तयार होते",
        "Report kaise banti hai",
    ),
    "custody-liability-report.steps.0.label": (
        "Pick Person",
        "व्यक्ति चुनें",
        "व्यक्ती निवडा",
        "Person Pick karein",
    ),
    "custody-liability-report.steps.0.caption": (
        "Yourself by default; managers/admins can search any user",
        "डिफ़ॉल्ट रूप से आप स्वयं; managers/admins किसी भी user को खोज सकते हैं",
        "डिफॉल्टनुसार तुम्ही स्वतः; managers/admins कोणत्याही user ला शोधू शकतात",
        "Default mein aap khud; managers/admins kisi bhi user ko search kar sakte hain",
    ),
    "custody-liability-report.steps.1.label": (
        "Report Loads",
        "Report लोड होती है",
        "Report लोड होते",
        "Report Load hoti hai",
    ),
    "custody-liability-report.steps.1.caption": (
        "Pulls that person's currently active custody assignments",
        "उस व्यक्ति की वर्तमान में active custody assignments को खींचती है",
        "त्या व्यक्तीच्या सध्या active असलेल्या custody assignments आणते",
        "Us person ke currently active custody assignments ko fetch karti hai",
    ),
    "custody-liability-report.steps.2.label": (
        "Review Totals",
        "Totals की समीक्षा करें",
        "Totals चे पुनरावलोकन करा",
        "Totals Review karein",
    ),
    "custody-liability-report.steps.2.caption": (
        "Item count, original cost, and current book value side by side",
        "Item count, original cost, और current book value एक साथ (side by side)",
        "Item count, original cost, आणि current book value एकत्र (side by side)",
        "Item count, original cost, aur current book value side by side",
    ),
    "custody-liability-report.steps.3.label": (
        "Export",
        "Export करें",
        "Export करा",
        "Export karein",
    ),
    "custody-liability-report.steps.3.caption": (
        "Download the table as Excel (CSV) or PDF for handover/audit",
        "Handover/audit के लिए table को Excel (CSV) या PDF के रूप में download करें",
        "Handover/audit साठी table Excel (CSV) किंवा PDF स्वरूपात download करा",
        "Handover/audit ke liye table ko Excel (CSV) ya PDF format mein download karein",
    ),
    "custody-liability-report.fieldRules.0.name": (
        "Whose assets",
        "किसके Assets",
        "कोणाचे Assets",
        "Kiske Assets",
    ),
    "custody-liability-report.fieldRules.0.description": (
        "Selects which person's custody records to load; nothing renders until someone is picked",
        "यह तय करता है कि किस व्यक्ति के custody records लोड किए जाएं; जब तक कोई व्यक्ति नहीं चुना जाता, कुछ भी नहीं दिखता",
        "कोणत्या व्यक्तीचे custody records लोड करायचे हे निवडते; जोपर्यंत कोणीतरी निवडले जात नाही तोपर्यंत काहीही दिसत नाही",
        "Ye decide karta hai ki kis person ke custody records load hon; jab tak koi pick nahi hota, kuch bhi render nahi hota",
    ),
    "custody-liability-report.fieldRules.1.name": (
        "Item",
        "Item",
        "Item",
        "Item",
    ),
    "custody-liability-report.fieldRules.1.description": (
        "Asset name plus its asset code, shown together to tell apart similarly named assets",
        "Asset का नाम उसके asset code के साथ, ताकि मिलते-जुलते नाम वाले assets को अलग पहचाना जा सके",
        "Asset चे नाव त्याच्या asset code सह एकत्र दाखवले जाते, जेणेकरून सारखी नावे असलेल्या assets मध्ये फरक करता येईल",
        "Asset ka naam uske asset code ke saath dikhaya jaata hai, taaki similar naam wale assets ko alag pehchana ja sake",
    ),
    "custody-liability-report.fieldRules.2.name": (
        "Original price",
        "Original Price",
        "Original Price",
        "Original Price",
    ),
    "custody-liability-report.fieldRules.2.description": (
        "Acquisition cost recorded when the asset was purchased; never changes",
        "Asset खरीदे जाने पर दर्ज की गई acquisition cost; यह कभी नहीं बदलती",
        "Asset खरेदी केल्यावर नोंदवलेली acquisition cost; ती कधीही बदलत नाही",
        "Asset purchase hone par record ki gayi acquisition cost; ye kabhi change nahi hoti",
    ),
    "custody-liability-report.fieldRules.3.name": (
        "Value now",
        "Value Now",
        "Value Now",
        "Value Now",
    ),
    "custody-liability-report.fieldRules.3.description": (
        "Net book value after depreciation — what the person is currently liable for",
        "Depreciation के बाद net book value — जिसके लिए व्यक्ति वर्तमान में उत्तरदायी है",
        "Depreciation नंतरची net book value — ज्यासाठी ती व्यक्ती सध्या जबाबदार आहे",
        "Depreciation ke baad net book value — jiske liye person currently liable hai",
    ),
    "custody-liability-report.tip.title": (
        "The export buttons work; the API's PDF param doesn't",
        "Export buttons काम करते हैं; API का PDF param काम नहीं करता",
        "Export buttons काम करतात; API चा PDF param काम करत नाही",
        "Export buttons kaam karte hain; API ka PDF param kaam nahi karta",
    ),
    "custody-liability-report.tip.body": (
        "The Excel/PDF buttons in the table toolbar render client-side and always work. That's separate from this endpoint's own ?format=pdf query option, which is an unimplemented 501 stub on the backend — don't rely on it if you're calling the API directly.",
        "Table toolbar में मौजूद Excel/PDF buttons client-side पर render होते हैं और हमेशा काम करते हैं। यह इस endpoint के अपने ?format=pdf query option से अलग है, जो backend पर एक unimplemented 501 stub है — अगर आप सीधे API call कर रहे हैं तो इस पर निर्भर न रहें।",
        "Table toolbar मधील Excel/PDF buttons client-side वर render होतात आणि नेहमी काम करतात. हे या endpoint च्या स्वतःच्या ?format=pdf query option पेक्षा वेगळे आहे, जो backend वर एक unimplemented 501 stub आहे — जर तुम्ही थेट API call करत असाल तर यावर अवलंबून राहू नका.",
        "Table toolbar ke Excel/PDF buttons client-side par render hote hain aur hamesha kaam karte hain. Ye is endpoint ke apne ?format=pdf query option se alag hai, jo backend par ek unimplemented 501 stub hai — agar aap directly API call kar rahe hain to is par rely mat 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 CUSTODY_LIABILITY_REPORT.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(CUSTODY_LIABILITY_REPORT)} custody-liability-report keys.")


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