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

Usage: docker compose exec api python seed_translations_pageinfo_asset_transfer.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)
ASSET_TRANSFER = {
    "asset-transfer.title": (
        "Custody Transfer Workflow",
        "कस्टडी ट्रांसफर वर्कफ़्लो",
        "कस्टडी ट्रान्सफर वर्कफ्लो",
        "Custody Transfer Workflow",
    ),
    "asset-transfer.subtitle": (
        "Move custody of an asset to a new person with two-party sign-off",
        "किसी asset की custody को दो-पक्षीय sign-off के साथ नए व्यक्ति को स्थानांतरित करना",
        "एखाद्या asset ची custody दोन-पक्षीय sign-off सह नवीन व्यक्तीकडे हस्तांतरित करणे",
        "Kisi asset ki custody ko two-party sign-off ke saath naye person ko transfer karna",
    ),
    "asset-transfer.body.0": (
        "A transfer moves an asset's custody from its current holder to a new custodian. It never applies instantly — it stays pending until both sides have acted, so an asset can't silently change hands.",
        "एक transfer किसी asset की custody को उसके मौजूदा धारक से नए custodian को स्थानांतरित करता है। यह कभी तुरंत लागू नहीं होता — जब तक दोनों पक्ष कार्रवाई नहीं करते, तब तक यह pending बना रहता है, ताकि कोई asset चुपचाप हाथ न बदल सके।",
        "एक transfer एखाद्या asset ची custody तिच्या सध्याच्या धारकाकडून नवीन custodian कडे हस्तांतरित करतो. हे कधीही त्वरित लागू होत नाही — जोपर्यंत दोन्ही बाजू कृती करत नाहीत तोपर्यंत ते pending राहते, जेणेकरून एखादी asset गुपचूप हात बदलू शकत नाही.",
        "Ek transfer kisi asset ki custody ko uske current holder se naye custodian ko move karta hai. Ye kabhi turant apply nahi hota — jab tak dono sides action nahi lete, tab tak ye pending rehta hai, taaki koi asset chupke se hath na badle.",
    ),
    "asset-transfer.body.1": (
        "Start a transfer from Assigned Assets (click Transfer on a custody row) or by opening this page with a custody_id in the URL. The table below lists every transfer where you're either party, with inline actions for whichever step is yours.",
        "Assigned Assets से transfer शुरू करें (किसी custody row पर Transfer पर क्लिक करें) या इस पेज को URL में custody_id के साथ खोलकर। नीचे दी गई table में वे सभी transfer सूचीबद्ध हैं जिनमें आप किसी भी पक्ष के रूप में शामिल हैं, साथ ही जो भी step आपका है उसके लिए inline actions दिए गए हैं।",
        "Assigned Assets मधून transfer सुरू करा (एखाद्या custody row वर Transfer वर क्लिक करा) किंवा हे पेज URL मध्ये custody_id सह उघडून. खालील table मध्ये तेच सर्व transfer सूचीबद्ध आहेत ज्यात तुम्ही कोणत्याही बाजूने सामील आहात, तसेच जो कोणता step तुमचा असेल त्यासाठी inline actions दिलेले आहेत.",
        "Assigned Assets se transfer start karein (kisi custody row par Transfer par click karein) ya is page ko URL mein custody_id ke saath open karke. Neeche wali table mein wo saare transfers list hain jinme aap kisi bhi party ho, saath hi jo bhi step aapka hai uske liye inline actions diye gaye hain.",
    ),
    "asset-transfer.stepsHeading": (
        "Transfer lifecycle",
        "ट्रांसफर लाइफ़साइकल",
        "ट्रान्सफर लाइफसायकल",
        "Transfer lifecycle",
    ),
    "asset-transfer.steps.0.label": ("Initiate", "आरंभ करें", "सुरू करा", "Initiate"),
    "asset-transfer.steps.0.caption": (
        "Current custodian picks the new custodian and an optional effective date/reason.",
        "मौजूदा custodian नए custodian को चुनता है, साथ ही वैकल्पिक रूप से प्रभावी तिथि/कारण भी।",
        "सध्याचा custodian नवीन custodian निवडतो, तसेच पर्यायी प्रभावी तारीख/कारण.",
        "Current custodian naye custodian ko choose karta hai, saath hi optional effective date/reason.",
    ),
    "asset-transfer.steps.1.label": ("Pending Outgoing", "लंबित आउटगोइंग", "प्रलंबित आउटगोइंग", "Pending Outgoing"),
    "asset-transfer.steps.1.caption": (
        "Only the outgoing (current) custodian can Release.",
        "केवल outgoing (मौजूदा) custodian ही Release कर सकता है।",
        "फक्त outgoing (सध्याचा) custodian Release करू शकतो.",
        "Sirf outgoing (current) custodian hi Release kar sakta hai.",
    ),
    "asset-transfer.steps.2.label": ("Pending Incoming", "लंबित इनकमिंग", "प्रलंबित इनकमिंग", "Pending Incoming"),
    "asset-transfer.steps.2.caption": (
        "Only the incoming (new) custodian can Accept.",
        "केवल incoming (नया) custodian ही Accept कर सकता है।",
        "फक्त incoming (नवीन) custodian Accept करू शकतो.",
        "Sirf incoming (naya) custodian hi Accept kar sakta hai.",
    ),
    "asset-transfer.steps.3.label": ("Completed", "पूर्ण", "पूर्ण", "Completed"),
    "asset-transfer.steps.3.caption": (
        "Custody is now recorded under the new custodian.",
        "अब custody नए custodian के अंतर्गत दर्ज हो चुकी है।",
        "आता custody नवीन custodian च्या अंतर्गत नोंदवली गेली आहे.",
        "Ab custody naye custodian ke under record ho chuki hai.",
    ),
    "asset-transfer.fieldRules.0.name": ("New Custodian", "नया कस्टोडियन", "नवीन कस्टोडियन", "New Custodian"),
    "asset-transfer.fieldRules.0.description": (
        "Who the asset is being transferred to — searched from the user directory.",
        "asset किसे transfer किया जा रहा है — user directory से खोजा जाता है।",
        "asset कोणाकडे transfer केली जात आहे — user directory मधून शोधले जाते.",
        "Asset kise transfer kiya ja raha hai — user directory se search hota hai.",
    ),
    "asset-transfer.fieldRules.1.name": ("Effective Date", "प्रभावी तिथि", "प्रभावी तारीख", "Effective Date"),
    "asset-transfer.fieldRules.1.description": (
        "Optional; defaults to now if left blank.",
        "वैकल्पिक; खाली छोड़ने पर डिफ़ॉल्ट रूप से अभी (now) सेट हो जाता है।",
        "पर्यायी; रिकामे सोडल्यास डीफॉल्टपणे आत्ता (now) सेट होते.",
        "Optional hai; blank chhodne par by default abhi (now) set ho jaata hai.",
    ),
    "asset-transfer.fieldRules.2.name": ("Reason", "कारण", "कारण", "Reason"),
    "asset-transfer.fieldRules.2.description": (
        "Optional free-text note recorded with the transfer.",
        "वैकल्पिक फ्री-टेक्स्ट नोट जो transfer के साथ दर्ज होता है।",
        "पर्यायी फ्री-टेक्स्ट नोंद जी transfer सोबत नोंदवली जाते.",
        "Optional free-text note jo transfer ke saath record hota hai.",
    ),
    "asset-transfer.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "asset-transfer.fieldRules.3.description": (
        "pending_outgoing_signoff → pending_incoming_signoff → completed, or cancelled at either pending stage.",
        "pending_outgoing_signoff → pending_incoming_signoff → completed, या दोनों में से किसी भी pending चरण पर cancelled।",
        "pending_outgoing_signoff → pending_incoming_signoff → completed, किंवा दोन्हीपैकी कोणत्याही pending टप्प्यावर cancelled.",
        "pending_outgoing_signoff → pending_incoming_signoff → completed, ya dono pending stages mein se kisi par bhi cancelled ho sakta hai.",
    ),
    "asset-transfer.tip.title": (
        "Either party can cancel — but only their own action moves it",
        "कोई भी पक्ष cancel कर सकता है — लेकिन इसे आगे केवल अपनी ही कार्रवाई से बढ़ाया जा सकता है",
        "कोणताही पक्ष cancel करू शकतो — पण ते पुढे फक्त स्वतःच्याच कृतीने पुढे जाते",
        "Koi bhi party cancel kar sakti hai — lekin isse aage sirf apna khud ka action hi badhata hai",
    ),
    "asset-transfer.tip.body": (
        "A transfer that's never accepted stays pending indefinitely; it does not auto-expire. The outgoing custodian's Release and the incoming custodian's Accept are separate steps — one person (unless they're a super admin) can never complete both sides alone.",
        "जो transfer कभी accept नहीं होता, वह अनिश्चित काल तक pending रहता है; यह auto-expire नहीं होता। outgoing custodian का Release और incoming custodian का Accept अलग-अलग steps हैं — एक व्यक्ति (जब तक वह super admin न हो) कभी अकेले दोनों पक्ष पूरे नहीं कर सकता।",
        "जो transfer कधीच accept होत नाही, ते अनिश्चित काळापर्यंत pending राहते; ते auto-expire होत नाही. outgoing custodian चे Release आणि incoming custodian चे Accept हे वेगवेगळे steps आहेत — एक व्यक्ती (जोपर्यंत ती super admin नसेल) कधीही एकटी दोन्ही बाजू पूर्ण करू शकत नाही.",
        "Jo transfer kabhi accept nahi hota, wo indefinitely pending rehta hai; ye auto-expire nahi hota. Outgoing custodian ka Release aur incoming custodian ka Accept alag-alag steps hain — ek person (jab tak wo super admin na ho) kabhi akela dono sides complete nahi kar sakta.",
    ),
}


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 ASSET_TRANSFER.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(ASSET_TRANSFER)} asset-transfer keys.")


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