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

Usage: docker compose exec api python seed_translations_pageinfo_custody_bulk_reassign.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_BULK_REASSIGN = {
    "custody-bulk-reassign.title": (
        "Bulk Reassign Custody",
        "बल्क कस्टडी रीअसाइन",
        "बल्क कस्टडी रीअसाइन",
        "Bulk Custody Reassign",
    ),
    "custody-bulk-reassign.subtitle": (
        "Move every asset held by one custodian to another custodian in a single action.",
        "एक custodian के पास मौजूद सभी assets को एक ही action में दूसरे custodian को स्थानांतरित करें।",
        "एका custodian कडे असलेल्या सर्व assets एकाच action मध्ये दुसऱ्या custodian कडे हस्तांतरित करा.",
        "Ek custodian ke paas jo bhi assets hain, unhe ek hi action mein doosre custodian ko move karein.",
    ),
    "custody-bulk-reassign.body.0": (
        "Move multiple assets from one custodian to another in one action.",
        "एक ही action में कई assets को एक custodian से दूसरे custodian में स्थानांतरित करें।",
        "एकाच action मध्ये अनेक assets एका custodian कडून दुसऱ्या custodian कडे हस्तांतरित करा.",
        "Ek action mein multiple assets ek custodian se doosre custodian ko move karein.",
    ),
    "custody-bulk-reassign.body.1": (
        "Pick the outgoing custodian to load their currently active assets, choose the incoming custodian, "
        "tick the assets to move, then reassign. Only assets in active custody with this custodian are listed "
        "— anything already transferred or returned won't show up.",
        "जाने वाले (outgoing) custodian को चुनें ताकि उनके वर्तमान में active assets लोड हों, आने वाले (incoming) "
        "custodian को चुनें, जिन assets को move करना है उन्हें टिक करें, फिर reassign करें। केवल वे assets सूचीबद्ध "
        "होते हैं जो इस custodian के पास active custody में हैं — जो पहले ही transfer या return हो चुके हैं वे नहीं दिखेंगे।",
        "जाणाऱ्या (outgoing) custodian ला निवडा जेणेकरून त्यांच्या सध्याच्या active assets लोड होतील, येणाऱ्या "
        "(incoming) custodian ला निवडा, move करायच्या assets ला tick करा, नंतर reassign करा. फक्त या custodian कडे "
        "active custody मध्ये असलेल्या assets ची यादी दिसते — आधीच transfer किंवा return झालेल्या कोणत्याही गोष्टी दिसणार नाहीत.",
        "Outgoing custodian select karein taaki unke currently active assets load ho jaayein, incoming custodian "
        "choose karein, jo assets move karne hain unhe tick karein, phir reassign karein. Sirf wahi assets list "
        "hote hain jo is custodian ke paas active custody mein hain — jo already transfer ya return ho chuke hain "
        "wo nahi dikhenge.",
    ),
    "custody-bulk-reassign.stepsHeading": (
        "How a bulk reassign runs",
        "बल्क reassign कैसे काम करता है",
        "बल्क reassign कसे कार्य करते",
        "Bulk reassign kaise chalta hai",
    ),
    "custody-bulk-reassign.steps.0.label": ("Select From", "From चुनें", "From निवडा", "Select From"),
    "custody-bulk-reassign.steps.0.caption": (
        "Choose the outgoing custodian to load their assets.",
        "उनके assets लोड करने के लिए outgoing custodian चुनें।",
        "त्यांच्या assets लोड करण्यासाठी outgoing custodian निवडा.",
        "Unke assets load karne ke liye outgoing custodian choose karein.",
    ),
    "custody-bulk-reassign.steps.1.label": ("Select To", "To चुनें", "To निवडा", "Select To"),
    "custody-bulk-reassign.steps.1.caption": (
        "Choose the new custodian (can't be the same person).",
        "नया custodian चुनें (यह वही व्यक्ति नहीं हो सकता)।",
        "नवीन custodian निवडा (हा तोच व्यक्ती असू शकत नाही).",
        "Naya custodian choose karein (same person nahi ho sakta).",
    ),
    "custody-bulk-reassign.steps.2.label": ("Pick Assets", "Assets चुनें", "Assets निवडा", "Assets Pick Karein"),
    "custody-bulk-reassign.steps.2.caption": (
        "Check each active asset you want to move.",
        "जिन active assets को move करना है, उन्हें check करें।",
        "ज्या active assets move करायच्या आहेत त्या प्रत्येकीला check करा.",
        "Jo active assets move karne hain, un sabko check karein.",
    ),
    "custody-bulk-reassign.steps.3.label": ("Reassign", "Reassign करें", "Reassign करा", "Reassign Karein"),
    "custody-bulk-reassign.steps.3.caption": (
        "Submit — moved assets are cleared, failures stay checked.",
        "Submit करें — स्थानांतरित assets clear हो जाते हैं, विफल (failed) assets checked रहते हैं।",
        "Submit करा — हस्तांतरित झालेल्या assets clear होतात, अयशस्वी (failed) assets checked राहतात.",
        "Submit karein — jo assets move ho jaate hain wo clear ho jaate hain, jo fail hote hain wo checked hi rehte hain.",
    ),
    "custody-bulk-reassign.fieldRules.0.name": ("From Custodian", "From Custodian", "From Custodian", "From Custodian"),
    "custody-bulk-reassign.fieldRules.0.description": (
        "Whose active assets to list; changing this reloads the asset list below and clears any checked items.",
        "किसके active assets सूचीबद्ध करने हैं; इसे बदलने पर नीचे asset list फिर से लोड होती है और checked items clear हो जाते हैं।",
        "कोणाच्या active assets ची यादी दाखवायची; हे बदलल्यास खालील asset list पुन्हा लोड होते आणि checked items clear होतात.",
        "Kiske active assets list karne hain; ise change karne par neeche ki asset list reload ho jaati hai aur checked items clear ho jaate hain.",
    ),
    "custody-bulk-reassign.fieldRules.1.name": ("To Custodian", "To Custodian", "To Custodian", "To Custodian"),
    "custody-bulk-reassign.fieldRules.1.description": (
        "Receiving custodian; the From custodian is automatically excluded from this list.",
        "प्राप्त करने वाला (receiving) custodian; From custodian इस सूची से स्वचालित रूप से बाहर रखा जाता है।",
        "प्राप्त करणारा (receiving) custodian; From custodian या यादीतून आपोआप वगळला जातो.",
        "Receiving custodian; From custodian ko is list se automatically exclude kar diya jaata hai.",
    ),
    "custody-bulk-reassign.fieldRules.2.name": (
        "Active assets held by this custodian",
        "इस custodian के पास मौजूद active assets",
        "या custodian कडे असलेल्या active assets",
        "Is custodian ke paas jo active assets hain",
    ),
    "custody-bulk-reassign.fieldRules.2.description": (
        "At least one asset must be checked — the Reassign button stays disabled until then.",
        "कम से कम एक asset check होना चाहिए — तब तक Reassign बटन disabled रहता है।",
        "किमान एक asset check केलेली असणे आवश्यक आहे — तोपर्यंत Reassign बटण disabled राहते.",
        "Kam se kam ek asset check hona chahiye — tab tak Reassign button disabled rehta hai.",
    ),
    "custody-bulk-reassign.tip.title": (
        "Partial failures stay selected",
        "आंशिक विफलताएँ selected रहती हैं",
        "आंशिक अपयश (failures) selected राहतात",
        "Partial failures selected hi rehte hain",
    ),
    "custody-bulk-reassign.tip.body": (
        "If some assets fail to transfer (e.g. one is mid-approval elsewhere), the toast reports how many "
        "succeeded and the failed ones remain checked — just hit Reassign again to retry only those.",
        "यदि कुछ assets transfer होने में विफल रहते हैं (उदाहरण के लिए, कोई एक कहीं और mid-approval में है), तो toast "
        "बताता है कि कितने सफल हुए और विफल assets checked ही रहते हैं — केवल उन्हीं को फिर से try करने के लिए दोबारा Reassign दबाएँ।",
        "जर काही assets transfer होण्यात अयशस्वी झाल्या (उदा. एखादी दुसरीकडे mid-approval मध्ये आहे), तर toast किती "
        "यशस्वी झाल्या ते सांगतो आणि अयशस्वी assets checked च राहतात — फक्त त्यांनाच पुन्हा try करण्यासाठी पुन्हा Reassign दाबा.",
        "Agar kuch assets transfer hone mein fail ho jaate hain (jaise koi ek kahin aur mid-approval mein hai), "
        "toast batata hai ki kitne successful hue aur jo fail hue wo checked hi rehte hain — sirf unhi ko retry "
        "karne ke liye dobara Reassign dabaayein.",
    ),
}


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_BULK_REASSIGN.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_BULK_REASSIGN)} custody-bulk-reassign keys.")


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