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

Usage: docker compose exec api python seed_translations_pageinfo_org_units_hierarchy.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)
ORG_UNITS_HIERARCHY = {
    "org-units-hierarchy.title": (
        "Company Hierarchy Visualizer",
        "कंपनी पदानुक्रम विज़ुअलाइज़र",
        "कंपनी श्रेणीरचना व्हिज्युअलायझर",
        "Company Hierarchy Visualizer",
    ),
    "org-units-hierarchy.subtitle": (
        "Read-only tree view of how every org unit nests under the ones above it",
        "यह एक रीड-ओनली ट्री व्यू है जो दिखाता है कि हर org unit अपने ऊपर वाली unit के अंदर किस तरह nest होती है।",
        "ही एक रीड-ओनली ट्री व्ह्यू आहे जी दाखवते की प्रत्येक org unit तिच्या वरील unit च्या आत कशी nest होते.",
        "Read-only tree view jo dikhata hai ki har org unit apne upar wali unit ke andar kaise nest hoti hai.",
    ),
    "org-units-hierarchy.body.0": (
        "Visual tree of how every organisation unit relates to the others.",
        "यह एक विज़ुअल ट्री है जो दिखाता है कि हर organisation unit दूसरी units से कैसे जुड़ी है।",
        "ही एक व्हिज्युअल ट्री आहे जी दाखवते की प्रत्येक organisation unit इतर units शी कशी जोडलेली आहे.",
        "Visual tree jo dikhata hai ki har organisation unit doosri units se kaise related hai.",
    ),
    "org-units-hierarchy.body.1": (
        "Click any node on the left to inspect its details, legal/tax identifiers and child-unit counts on the right. This page is view-only — use Org Units (Back to Units) to create, edit or approve units.",
        "बाईं ओर किसी भी node पर क्लिक करें ताकि दाईं ओर उसकी details, legal/tax identifiers और child-unit की गिनती देखी जा सके। यह पेज केवल view करने के लिए है — units बनाने, edit करने या approve करने के लिए Org Units (Back to Units) का उपयोग करें।",
        "डावीकडे कोणत्याही node वर क्लिक करा जेणेकरून उजवीकडे त्याचे details, legal/tax identifiers आणि child-unit ची संख्या पाहता येईल. हे पेज फक्त view करण्यासाठी आहे — units तयार करण्यासाठी, edit करण्यासाठी किंवा approve करण्यासाठी Org Units (Back to Units) वापरा.",
        "Left side par kisi bhi node par click karein taaki right side par uski details, legal/tax identifiers aur child-unit count dekh sakein. Ye page sirf view karne ke liye hai — units create, edit ya approve karne ke liye Org Units (Back to Units) use karein.",
    ),
    "org-units-hierarchy.stepsHeading": (
        "How to read the tree",
        "ट्री को कैसे पढ़ें",
        "ट्री कशी वाचावी",
        "Tree ko kaise padhein",
    ),
    "org-units-hierarchy.steps.0.label": ("Root Nodes", "रूट नोड्स", "रूट नोड्स", "Root Nodes"),
    "org-units-hierarchy.steps.0.caption": (
        "Top-level units with no parent; first one auto-selected on load",
        "बिना parent वाली सबसे ऊपर की units; लोड होने पर पहली इकाई अपने-आप select हो जाती है",
        "parent नसलेल्या सर्वात वरच्या units; लोड झाल्यावर पहिली unit आपोआप select होते",
        "Bina parent wali top-level units; load hone par pehli unit apne aap select ho jaati hai",
    ),
    "org-units-hierarchy.steps.1.label": ("Select a Node", "एक Node चुनें", "एक Node निवडा", "Ek Node Select Karein"),
    "org-units-hierarchy.steps.1.caption": (
        "Click any unit, at any depth, to load it into the Inspector",
        "किसी भी depth पर किसी भी unit पर क्लिक करें ताकि वह Inspector में लोड हो जाए",
        "कोणत्याही depth वरील कोणत्याही unit वर क्लिक करा जेणेकरून ती Inspector मध्ये लोड होईल",
        "Kisi bhi depth par kisi bhi unit par click karein taaki wo Inspector mein load ho jaaye",
    ),
    "org-units-hierarchy.steps.2.label": ("Inspect Details", "Details का निरीक्षण करें", "Details तपासा", "Details Inspect Karein"),
    "org-units-hierarchy.steps.2.caption": (
        "Basic info, plus Legal & Tax fields when the unit has any set",
        "बेसिक जानकारी, और यदि unit में कोई सेट है तो Legal & Tax fields भी",
        "बेसिक माहिती, आणि जर unit मध्ये काही सेट असेल तर Legal & Tax fields देखील",
        "Basic info, aur agar unit mein Legal & Tax fields set hain to wo bhi",
    ),
    "org-units-hierarchy.steps.3.label": ("Check Metrics", "Metrics जांचें", "Metrics तपासा", "Metrics Check Karein"),
    "org-units-hierarchy.steps.3.caption": (
        "Direct children, total descendants, and legal-entity flag",
        "Direct children, total descendants, और legal-entity flag",
        "Direct children, total descendants, आणि legal-entity flag",
        "Direct children, total descendants, aur legal-entity flag",
    ),
    "org-units-hierarchy.fieldRules.0.name": ("Unit Name / Type", "यूनिट नाम / प्रकार", "युनिट नेम / टाईप", "Unit Name / Type"),
    "org-units-hierarchy.fieldRules.0.description": (
        "Node label and its ou_type badge (department, division, cpse, etc.).",
        "Node का label और उसका ou_type badge (department, division, cpse, आदि)।",
        "Node चा label आणि त्याचा ou_type badge (department, division, cpse, इ.).",
        "Node ka label aur uska ou_type badge (department, division, cpse, etc.).",
    ),
    "org-units-hierarchy.fieldRules.1.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "org-units-hierarchy.fieldRules.1.description": (
        "Real lifecycle state of the selected unit — active, pending_approval, dissolved.",
        "चुनी गई unit की वास्तविक lifecycle स्थिति — active, pending_approval, dissolved।",
        "निवडलेल्या unit ची वास्तविक lifecycle स्थिती — active, pending_approval, dissolved.",
        "Selected unit ki real lifecycle state — active, pending_approval, dissolved.",
    ),
    "org-units-hierarchy.fieldRules.2.name": ("Legal & Tax Info", "Legal & Tax जानकारी", "Legal & Tax माहिती", "Legal & Tax Info"),
    "org-units-hierarchy.fieldRules.2.description": (
        "CIN / PAN / GSTIN / Cost Centre Code — section only appears if the unit has at least one set.",
        "CIN / PAN / GSTIN / Cost Centre Code — यह सेक्शन तभी दिखता है जब unit में कम से कम एक फ़ील्ड सेट हो।",
        "CIN / PAN / GSTIN / Cost Centre Code — हा सेक्शन तेव्हाच दिसतो जेव्हा unit मध्ये किमान एक फील्ड सेट असते.",
        "CIN / PAN / GSTIN / Cost Centre Code — ye section tabhi dikhta hai jab unit mein kam se kam ek field set ho.",
    ),
    "org-units-hierarchy.fieldRules.3.name": ("Hierarchy Metrics", "पदानुक्रम Metrics", "श्रेणीरचना Metrics", "Hierarchy Metrics"),
    "org-units-hierarchy.fieldRules.3.description": (
        "Direct Children counts one level down; Total Descendants counts the whole subtree.",
        "Direct Children एक स्तर नीचे तक गिनती करता है; Total Descendants पूरे subtree की गिनती करता है।",
        "Direct Children एक स्तर खालीपर्यंत मोजते; Total Descendants संपूर्ण subtree मोजते.",
        "Direct Children ek level neeche tak count karta hai; Total Descendants poore subtree ko count karta hai.",
    ),
    "org-units-hierarchy.tip.title": (
        "Tree badge can mislead",
        "Tree badge भ्रामक हो सकता है",
        "Tree badge दिशाभूल करू शकतो",
        "Tree Badge Misleading Ho Sakta Hai",
    ),
    "org-units-hierarchy.tip.body": (
        "The left-hand tree shows \"Active\" for both active AND pending_approval units. To see a node's real status, select it and read the Status badge in the Inspector on the right.",
        "बाईं ओर की tree active और pending_approval दोनों units के लिए \"Active\" दिखाती है। किसी node की असली स्थिति देखने के लिए, उसे select करें और दाईं ओर Inspector में Status badge पढ़ें।",
        "डावीकडील tree active आणि pending_approval अशा दोन्ही units साठी \"Active\" दाखवते. एखाद्या node ची खरी स्थिती पाहण्यासाठी, ती select करा आणि उजवीकडे Inspector मधील Status badge वाचा.",
        "Left-hand tree active aur pending_approval dono units ke liye \"Active\" dikhati hai. Kisi node ki real status dekhne ke liye, use select karein aur right side Inspector mein Status badge padhein.",
    ),
}


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 ORG_UNITS_HIERARCHY.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(ORG_UNITS_HIERARCHY)} org-units-hierarchy keys.")


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