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

Usage: docker compose exec api python seed_translations_pageinfo_department_masters.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)
DEPARTMENT_MASTERS = {
    "department-masters.title": (
        "Departments",
        "विभाग",
        "विभाग",
        "Departments",
    ),
    "department-masters.subtitle": (
        "How department records work and what governs them",
        "विभाग रिकॉर्ड कैसे काम करते हैं और उन्हें क्या नियंत्रित करता है",
        "विभाग रेकॉर्ड कसे कार्य करतात आणि त्यांना काय नियंत्रित करते",
        "Department records kaise kaam karte hain aur unhe kya control karta hai",
    ),
    "department-masters.body.0": (
        'A department is an OrgUnit with type "department", managed here through the Masters API (/masters/department) alongside the generic Org Units module.',
        'एक department एक OrgUnit होता है जिसका type "department" होता है, जिसे यहाँ Masters API (/masters/department) के ज़रिए generic Org Units module के साथ-साथ प्रबंधित किया जाता है।',
        'एक department म्हणजे "department" प्रकाराची OrgUnit असते, जी येथे Masters API (/masters/department) मार्फत सर्वसाधारण Org Units module सोबत व्यवस्थापित केली जाते.',
        'Department ek OrgUnit hota hai jiska type "department" hota hai, jise yahan Masters API (/masters/department) ke through generic Org Units module ke saath-saath manage kiya jaata hai.',
    ),
    "department-masters.body.1": (
        "Renaming, moving, dissolve history and restore are structural changes — they're handled on the full Org Unit Detail page (the tree icon in Actions), not on this form.",
        "नाम बदलना, स्थानांतरण, dissolve history और restore जैसे structural changes इस फ़ॉर्म पर नहीं, बल्कि पूरे Org Unit Detail पेज (Actions में tree icon) पर संभाले जाते हैं।",
        "नाव बदलणे, हलवणे, dissolve history आणि restore हे structural changes असून ते या फॉर्मवर नव्हे, तर संपूर्ण Org Unit Detail पेजवर (Actions मधील tree icon) हाताळले जातात.",
        "Renaming, moving, dissolve history aur restore structural changes hain — inhe is form par nahi, balki poore Org Unit Detail page (Actions mein tree icon) par handle kiya jaata hai.",
    ),
    "department-masters.stepsHeading": (
        "Department lifecycle",
        "Department lifecycle",
        "Department lifecycle",
        "Department lifecycle",
    ),
    "department-masters.steps.0.label": ("Created", "बनाया गया", "तयार केले", "Created"),
    "department-masters.steps.0.caption": (
        "Saved as pending approval",
        "pending approval के रूप में सेव किया गया",
        "pending approval म्हणून सेव्ह केले",
        "Pending approval ke roop mein save hota hai",
    ),
    "department-masters.steps.1.label": ("Pending Approval", "स्वीकृति लंबित", "मंजुरी प्रलंबित", "Pending Approval"),
    "department-masters.steps.1.caption": (
        "Awaiting a second user's sign-off",
        "किसी दूसरे user के sign-off का इंतज़ार",
        "दुसऱ्या user च्या sign-off ची प्रतीक्षा",
        "Doosre user ke sign-off ka wait rehta hai",
    ),
    "department-masters.steps.2.label": ("Active", "सक्रिय", "सक्रिय", "Active"),
    "department-masters.steps.2.caption": (
        "Approved; usable across the app",
        "स्वीकृत; पूरे app में उपयोग योग्य",
        "मंजूर; संपूर्ण app मध्ये वापरण्यायोग्य",
        "Approved ho jaata hai; poore app mein use ho sakta hai",
    ),
    "department-masters.steps.3.label": ("Dissolved", "भंग किया गया", "विसर्जित", "Dissolved"),
    "department-masters.steps.3.caption": (
        "Soft-deleted; restorable any time",
        "Soft-delete किया गया; किसी भी समय restore किया जा सकता है",
        "Soft-delete केलेले; कधीही restore करता येते",
        "Soft-delete ho jaata hai; kabhi bhi restore kiya ja sakta hai",
    ),
    "department-masters.fieldRules.0.name": ("Department Name", "विभाग का नाम", "विभागाचे नाव", "Department Name"),
    "department-masters.fieldRules.0.description": (
        "Required on create. Structural — locked on Edit; rename via Restructure instead.",
        "Create पर आवश्यक। यह structural है — Edit पर locked रहता है; इसके बजाय नाम बदलने के लिए Restructure का उपयोग करें।",
        "Create वेळी आवश्यक. हे structural आहे — Edit वर locked राहते; त्याऐवजी नाव बदलण्यासाठी Restructure वापरा.",
        "Create ke time required hota hai. Ye structural hai — Edit par locked rehta hai; rename karne ke liye iske bajaay Restructure use karein.",
    ),
    "department-masters.fieldRules.1.name": ("Parent Unit ID", "पैरेंट यूनिट ID", "पॅरेंट युनिट ID", "Parent Unit ID"),
    "department-masters.fieldRules.1.description": (
        "Optional parent OrgUnit UUID. Also structural — locked on Edit.",
        "वैकल्पिक parent OrgUnit UUID। यह भी structural है — Edit पर locked रहता है।",
        "पर्यायी parent OrgUnit UUID. हे देखील structural आहे — Edit वर locked राहते.",
        "Optional parent OrgUnit UUID hota hai. Ye bhi structural hai — Edit par locked rehta hai.",
    ),
    "department-masters.fieldRules.2.name": ("Cost Centre Code", "कॉस्ट सेंटर कोड", "कॉस्ट सेंटर कोड", "Cost Centre Code"),
    "department-masters.fieldRules.2.description": (
        "Free-text accounting code shown in the table; not checked against a master list.",
        "टेबल में दिखाया जाने वाला free-text accounting code; इसे किसी master list के विरुद्ध जाँचा नहीं जाता।",
        "टेबलमध्ये दाखवला जाणारा free-text accounting code; तो कोणत्याही master list विरुद्ध तपासला जात नाही.",
        "Table mein dikhne wala free-text accounting code hai; isse kisi master list ke against check nahi kiya jaata.",
    ),
    "department-masters.fieldRules.3.name": ("Approver Authority", "अनुमोदक प्राधिकरण", "मंजुरी प्राधिकरण", "Approver Authority"),
    "department-masters.fieldRules.3.description": (
        "Free-text note on who approves matters for this department.",
        "इस department के मामलों को कौन approve करता है, इस पर एक free-text नोट।",
        "या department च्या बाबी कोण मंजूर करते याबद्दल free-text टीप.",
        "Is department ke matters kaun approve karta hai, iske baare mein ek free-text note hota hai.",
    ),
    "department-masters.fieldRules.4.name": ("CIN / PAN / GSTIN", "CIN / PAN / GSTIN", "CIN / PAN / GSTIN", "CIN / PAN / GSTIN"),
    "department-masters.fieldRules.4.description": (
        "Auto-uppercased legal-entity identifiers; length-limited only, format isn't validated.",
        "Legal-entity identifiers जो automatically uppercase हो जाते हैं; केवल length सीमित है, format को validate नहीं किया जाता।",
        "Legal-entity identifiers जे आपोआप uppercase होतात; फक्त length मर्यादित आहे, format validate केले जात नाही.",
        "Legal-entity identifiers auto-uppercase ho jaate hain; sirf length limited hoti hai, format validate nahi kiya jaata.",
    ),
    "department-masters.tip.title": (
        "Can't edit the name or parent?",
        "नाम या parent edit नहीं कर पा रहे?",
        "नाव किंवा parent edit करता येत नाही?",
        "Naam ya parent edit nahi ho raha?",
    ),
    "department-masters.tip.body": (
        "That's expected — PATCH on this page only updates cost centre, approver authority and legal/identifier fields. To rename or move a department, use the account_tree (Restructure) icon in its row instead.",
        "यह अपेक्षित है — इस पेज पर PATCH केवल cost centre, approver authority और legal/identifier fields को update करता है। किसी department का नाम बदलने या उसे move करने के लिए, इसके बजाय उसकी row में account_tree (Restructure) icon का उपयोग करें।",
        "हे अपेक्षितच आहे — या पेजवरील PATCH फक्त cost centre, approver authority आणि legal/identifier fields अपडेट करते. एखाद्या department चे नाव बदलण्यासाठी किंवा ते move करण्यासाठी, त्याऐवजी त्याच्या row मधील account_tree (Restructure) icon वापरा.",
        "Ye expected hai — is page par PATCH sirf cost centre, approver authority aur legal/identifier fields update karta hai. Kisi department ka naam badalne ya use move karne ke liye, iske bajaay uski row mein account_tree (Restructure) icon use 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 DEPARTMENT_MASTERS.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(DEPARTMENT_MASTERS)} department-masters keys.")


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