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

Usage: docker compose exec api python seed_translations_pageinfo_custody_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)
CUSTODY_ASSIGN = {
    "custody-assign.title": (
        "Assign Custodian",
        "कस्टोडियन असाइन करें",
        "कस्टोडियन असाइन करा",
        "Custodian Assign Karein",
    ),
    "custody-assign.subtitle": (
        "Hand accountability for an asset to a person, pending their acceptance.",
        "किसी asset की जवाबदेही किसी व्यक्ति को सौंपें, उनकी स्वीकृति लंबित रहते हुए।",
        "एखाद्या asset ची जबाबदारी एखाद्या व्यक्तीकडे सोपवा, त्यांच्या स्वीकृतीच्या प्रतीक्षेत.",
        "Asset ki accountability kisi person ko hand karein, unki acceptance pending rehte hue.",
    ),
    "custody-assign.body.0": (
        "Use this page to hand an asset over to the person who will be responsible for it.",
        "किसी asset को उस व्यक्ति को सौंपने के लिए इस पेज का उपयोग करें जो इसके लिए ज़िम्मेदार होगा।",
        "एखादी asset त्या व्यक्तीकडे सोपवण्यासाठी हे पेज वापरा जी त्यासाठी जबाबदार असेल.",
        "Kisi asset ko us person ko hand karne ke liye ye page use karein jo uske liye responsible hoga.",
    ),
    "custody-assign.body.1": (
        "Once assigned, that person becomes accountable for the asset until it's transferred or returned.",
        "एक बार असाइन हो जाने पर, वह व्यक्ति asset के लिए तब तक जवाबदेह होता है जब तक इसे transfer या return नहीं किया जाता।",
        "एकदा असाइन झाल्यावर, ती व्यक्ती asset साठी जबाबदार राहते जोपर्यंत ती transfer किंवा return केली जात नाही.",
        "Ek baar assign hone ke baad, wo person asset ke liye accountable ho jaata hai jab tak ise transfer ya return na kiya jaaye.",
    ),
    "custody-assign.body.2": (
        "Submitting this form supersedes any prior active custody record for the asset — the previous custodian is replaced, not added to.",
        "यह फ़ॉर्म सबमिट करने पर asset के किसी भी पिछले active custody record की जगह यह नया रिकॉर्ड ले लेता है — पिछला custodian बदल दिया जाता है, जोड़ा नहीं जाता।",
        "हा फॉर्म सबमिट केल्यास asset च्या आधीच्या कोणत्याही active custody record ची जागा हा नवीन रेकॉर्ड घेतो — मागील custodian बदलला जातो, तो जोडला जात नाही.",
        "Ye form submit karne se asset ke kisi bhi prior active custody record ki jagah ye naya record le leta hai — previous custodian replace hota hai, add nahi hota.",
    ),
    "custody-assign.stepsHeading": (
        "How assignment flows",
        "असाइनमेंट कैसे आगे बढ़ता है",
        "असाइनमेंट कसे पुढे जाते",
        "Assignment kaise flow karta hai",
    ),
    "custody-assign.steps.0.label": ("Assign", "असाइन करें", "असाइन करा", "Assign"),
    "custody-assign.steps.0.caption": (
        "Asset Manager submits asset, custodian, and optional org unit / effective date.",
        "Asset Manager asset, custodian, और वैकल्पिक org unit / effective date सबमिट करता है।",
        "Asset Manager asset, custodian, आणि पर्यायी org unit / effective date सबमिट करतो.",
        "Asset Manager asset, custodian, aur optional org unit / effective date submit karta hai.",
    ),
    "custody-assign.steps.1.label": ("Pending Acceptance", "स्वीकृति लंबित", "स्वीकृती प्रलंबित", "Pending Acceptance"),
    "custody-assign.steps.1.caption": (
        "Custodian sees it queued on Assigned Assets — they're not yet accountable.",
        "Custodian इसे Assigned Assets पर कतार में देखता है — वे अभी तक जवाबदेह नहीं होते।",
        "Custodian ते Assigned Assets वर रांगेत पाहतो — तो अजून जबाबदार नसतो.",
        "Custodian ise Assigned Assets par queued dekhta hai — wo abhi tak accountable nahi hota.",
    ),
    "custody-assign.steps.2.label": ("Accepted / Active", "स्वीकृत / सक्रिय", "स्वीकृत / सक्रिय", "Accepted / Active"),
    "custody-assign.steps.2.caption": (
        "Custodian accepts; this becomes the asset's current active custody.",
        "Custodian स्वीकृति देता है; यह asset का वर्तमान active custody बन जाता है।",
        "Custodian स्वीकृती देतो; हे asset ची सध्याची active custody बनते.",
        "Custodian accept karta hai; ye asset ki current active custody ban jaati hai.",
    ),
    "custody-assign.steps.3.label": ("Superseded", "अधिक्रमित", "अधिक्रमित", "Superseded"),
    "custody-assign.steps.3.caption": (
        "A later assignment to a new custodian replaces this record automatically.",
        "किसी नए custodian को बाद में की गई assignment इस record को स्वतः बदल देती है।",
        "नवीन custodian ला नंतर केलेली assignment हा record आपोआप बदलते.",
        "Kisi naye custodian ko baad mein ki gayi assignment is record ko automatically replace kar deti hai.",
    ),
    "custody-assign.fieldRules.0.name": ("Asset", "एसेट", "एसेट", "Asset"),
    "custody-assign.fieldRules.0.description": (
        "The asset changing hands; searchable, shows asset ref and name.",
        "वह asset जो हाथ बदल रहा है; searchable है, asset ref और नाम दिखाता है।",
        "हात बदलणारी asset; searchable आहे, asset ref आणि नाव दाखवते.",
        "Wo asset jo hands change kar raha hai; searchable hai, asset ref aur name dikhata hai.",
    ),
    "custody-assign.fieldRules.1.name": ("Custodian", "कस्टोडियन", "कस्टोडियन", "Custodian"),
    "custody-assign.fieldRules.1.description": (
        "Person taking responsibility; list is scoped to custody-eligible users, shown with email since names can repeat.",
        "ज़िम्मेदारी लेने वाला व्यक्ति; सूची custody-eligible users तक सीमित है, नाम दोहराए जा सकते हैं इसलिए email के साथ दिखाया जाता है।",
        "जबाबदारी घेणारी व्यक्ती; यादी custody-eligible users पुरती मर्यादित आहे, नावे पुनरावृत्त होऊ शकतात म्हणून email सह दाखवली जाते.",
        "Responsibility lene wala person; list custody-eligible users tak scoped hai, names repeat ho sakte hain isliye email ke saath dikhaya jaata hai.",
    ),
    "custody-assign.fieldRules.2.name": ("Org Unit (optional)", "Org Unit (वैकल्पिक)", "Org Unit (पर्यायी)", "Org Unit (optional)"),
    "custody-assign.fieldRules.2.description": (
        "Optional org-unit context for the custody; leave as None if not needed.",
        "custody के लिए वैकल्पिक org-unit संदर्भ; ज़रूरत न होने पर None ही रहने दें।",
        "custody साठी पर्यायी org-unit संदर्भ; गरज नसल्यास None तसेच ठेवा.",
        "Custody ke liye optional org-unit context; zaroorat na ho to None hi rehne dein.",
    ),
    "custody-assign.fieldRules.3.name": (
        "Effective From (optional — defaults to now)",
        "प्रभावी तिथि (वैकल्पिक — डिफ़ॉल्ट रूप से अभी)",
        "प्रभावी तारीख (पर्यायी — डीफॉल्टनुसार आत्ता)",
        "Effective From (optional — default abhi ka time)",
    ),
    "custody-assign.fieldRules.3.description": (
        "When custody starts; leave blank to use the submission time.",
        "custody कब शुरू होती है; submission के समय का उपयोग करने के लिए इसे खाली छोड़ दें।",
        "custody कधी सुरू होते; submission च्या वेळेचा वापर करण्यासाठी हे रिकामे ठेवा.",
        "Custody kab start hoti hai; submission ke time ko use karne ke liye ise blank chhod dein.",
    ),
    "custody-assign.tip.title": (
        "Acceptance is a separate step",
        "स्वीकृति एक अलग चरण है",
        "स्वीकृती हा एक वेगळा टप्पा आहे",
        "Acceptance ek alag step hai",
    ),
    "custody-assign.tip.body": (
        "Assigning replaces the prior active custody immediately with no confirmation prompt — but the new custodian isn't accountable until they accept it from the Assigned Assets page.",
        "Assign करने से पिछली active custody तुरंत बदल दी जाती है, बिना किसी confirmation prompt के — लेकिन नया custodian तब तक जवाबदेह नहीं होता जब तक वह इसे Assigned Assets पेज से स्वीकार नहीं करता।",
        "Assign केल्याने आधीची active custody लगेच बदलली जाते, कोणत्याही confirmation prompt शिवाय — पण नवीन custodian तोपर्यंत जबाबदार नसतो जोपर्यंत तो Assigned Assets पेजवरून ती स्वीकारत नाही.",
        "Assign karne se prior active custody turant replace ho jaati hai, koi confirmation prompt nahi hota — lekin naya custodian tab tak accountable nahi hota jab tak wo ise Assigned Assets page se accept nahi karta.",
    ),
}


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_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(CUSTODY_ASSIGN)} custody-assign keys.")


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