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

Usage: docker compose exec api python seed_translations_pageinfo_custody_investigations.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_INVESTIGATIONS = {
    "custody-investigations.title": (
        "Audit Investigations",
        "ऑडिट जांच",
        "ऑडिट चौकशी",
        "Audit Investigations",
    ),
    "custody-investigations.subtitle": (
        "Track flagged custody events from open to close",
        "फ़्लैग किए गए custody events को open से close तक ट्रैक करें",
        "फ्लॅग केलेल्या custody events चा open पासून close पर्यंत मागोवा घ्या",
        "Flagged custody events ko open se close tak track karein",
    ),
    "custody-investigations.body.0": (
        "An investigation is opened against an asset when a custody dispute, verification mismatch, unauthorized transfer, or other flagged event needs to be looked into.",
        "जब किसी asset से जुड़े custody dispute, verification mismatch, unauthorized transfer, या किसी अन्य flagged event की जांच करनी होती है, तो उस asset के विरुद्ध एक investigation खोली जाती है।",
        "जेव्हा एखाद्या asset शी संबंधित custody dispute, verification mismatch, unauthorized transfer, किंवा इतर कोणत्याही flagged event ची चौकशी करणे आवश्यक असते, तेव्हा त्या asset विरुद्ध एक investigation उघडली जाते.",
        "Jab kisi asset se juda custody dispute, verification mismatch, unauthorized transfer, ya koi aur flagged event dekhna zaroori hota hai, tab us asset ke against ek investigation open ki jaati hai.",
    ),
    "custody-investigations.body.1": (
        "Only users with audit:write can open a new investigation or manage an existing one; other roles see the list read-only.",
        "केवल audit:write अनुमति वाले users ही नई investigation खोल सकते हैं या मौजूदा investigation को manage कर सकते हैं; अन्य roles को यह सूची केवल read-only रूप में दिखती है।",
        "फक्त audit:write परवानगी असलेले users नवीन investigation उघडू शकतात किंवा विद्यमान investigation manage करू शकतात; इतर roles ना ही यादी फक्त read-only स्वरूपात दिसते.",
        "Sirf audit:write permission wale users hi nayi investigation open kar sakte hain ya existing investigation ko manage kar sakte hain; baaki roles ko ye list sirf read-only dikhti hai.",
    ),
    "custody-investigations.stepsHeading": (
        "Investigation lifecycle",
        "Investigation जीवनचक्र",
        "Investigation जीवनचक्र",
        "Investigation ka lifecycle",
    ),
    "custody-investigations.steps.0.label": ("Open", "ओपन", "ओपन", "Open"),
    "custody-investigations.steps.0.caption": (
        "Created against an asset with a trigger type",
        "किसी asset के विरुद्ध एक trigger type के साथ बनाई गई",
        "एखाद्या asset विरुद्ध एका trigger type सह तयार केली",
        "Kisi asset ke against ek trigger type ke saath create hoti hai",
    ),
    "custody-investigations.steps.1.label": ("In Progress", "इन प्रोग्रेस", "इन प्रोग्रेस", "In Progress"),
    "custody-investigations.steps.1.caption": (
        "Being reviewed; notes capture findings",
        "समीक्षा की जा रही है; notes में findings दर्ज की जाती हैं",
        "पुनरावलोकन केले जात आहे; notes मध्ये findings नोंदवल्या जातात",
        "Review ho rahi hoti hai; notes mein findings capture hoti hain",
    ),
    "custody-investigations.steps.2.label": ("Resolved", "रिज़ॉल्व्ड", "रिझॉल्व्हड", "Resolved"),
    "custody-investigations.steps.2.caption": (
        "Outcome reached, resolved date recorded",
        "outcome तय हो जाता है, resolved date दर्ज की जाती है",
        "outcome निश्चित होतो, resolved date नोंदवली जाते",
        "Outcome decide ho jaata hai, resolved date record hoti hai",
    ),
    "custody-investigations.steps.3.label": ("Closed", "क्लोज़्ड", "क्लोज्ड", "Closed"),
    "custody-investigations.steps.3.caption": (
        "Case closed; kept for audit history",
        "केस बंद कर दिया जाता है; audit history के लिए रखा जाता है",
        "केस बंद केली जाते; audit history साठी ठेवली जाते",
        "Case close ho jaata hai; audit history ke liye rakha jaata hai",
    ),
    "custody-investigations.fieldRules.0.name": ("Asset", "Asset", "Asset", "Asset"),
    "custody-investigations.fieldRules.0.description": (
        "The asset the investigation is opened against; searched by ref or name",
        "वह asset जिसके विरुद्ध investigation खोली गई है; ref या name से खोजा जाता है",
        "ती asset ज्याविरुद्ध investigation उघडली आहे; ref किंवा name ने शोधली जाते",
        "Wo asset jiske against investigation open ki gayi hai; ref ya name se search kiya jaata hai",
    ),
    "custody-investigations.fieldRules.1.name": ("Trigger Type", "Trigger Type", "Trigger Type", "Trigger Type"),
    "custody-investigations.fieldRules.1.description": (
        "Why the case was opened, e.g. custody dispute or verification mismatch",
        "case क्यों खोला गया, जैसे custody dispute या verification mismatch",
        "केस का उघडले गेले, उदा. custody dispute किंवा verification mismatch",
        "Case kyun open hua tha, jaise custody dispute ya verification mismatch",
    ),
    "custody-investigations.fieldRules.2.name": ("Status", "Status", "Status", "Status"),
    "custody-investigations.fieldRules.2.description": (
        "Open, In Progress, Resolved, or Closed — set from the Manage dialog",
        "Open, In Progress, Resolved, या Closed — Manage dialog से सेट किया जाता है",
        "Open, In Progress, Resolved, किंवा Closed — Manage dialog मधून सेट केले जाते",
        "Open, In Progress, Resolved, ya Closed — Manage dialog se set hota hai",
    ),
    "custody-investigations.fieldRules.3.name": ("Notes", "Notes", "Notes", "Notes"),
    "custody-investigations.fieldRules.3.description": (
        "Free-text findings; left blank clears any previously saved notes",
        "फ्री-टेक्स्ट findings; खाली छोड़ने पर पहले से saved कोई भी notes हट जाते हैं",
        "फ्री-टेक्स्ट findings; रिकामे सोडल्यास आधी saved केलेल्या कोणत्याही notes हटवल्या जातात",
        "Free-text findings; blank chhodne par pehle se saved koi bhi notes clear ho jaate hain",
    ),
    "custody-investigations.tip.title": (
        "Asset showing as raw ID?",
        "Asset raw ID के रूप में दिख रहा है?",
        "Asset raw ID म्हणून दिसत आहे का?",
        "Asset raw ID jaisa dikh raha hai?",
    ),
    "custody-investigations.tip.body": (
        "If the Asset column shows a UUID instead of a name, the referenced asset couldn't be looked up (e.g. it was deleted) — this doesn't mean the investigation record is broken.",
        "अगर Asset कॉलम में नाम की जगह UUID दिख रहा है, तो इसका मतलब है कि संदर्भित asset को खोजा नहीं जा सका (जैसे कि उसे delete कर दिया गया था) — इसका यह मतलब नहीं कि investigation रिकॉर्ड खराब है।",
        "जर Asset कॉलममध्ये नावाऐवजी UUID दिसत असेल, तर याचा अर्थ संदर्भित asset शोधता आली नाही (उदा. ती delete केली गेली होती) — याचा अर्थ investigation रेकॉर्ड खराब आहे असे नाही.",
        "Agar Asset column mein naam ki jagah UUID dikh raha hai, to iska matlab hai ki referenced asset ko dhoonda nahi ja saka (jaise ki wo delete ho gaya tha) — iska ye matlab nahi ki investigation record kharab hai.",
    ),
}


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_INVESTIGATIONS.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_INVESTIGATIONS)} custody-investigations keys.")


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