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

Usage: docker compose exec api python seed_translations_pageinfo_org_unit_detail.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_UNIT_DETAIL = {
    "org-unit-detail.title": (
        "Organisation Unit Details",
        "ऑर्गनाइज़ेशन यूनिट विवरण",
        "ऑर्गनायझेशन युनिट तपशील",
        "Organisation Unit Details",
    ),
    "org-unit-detail.subtitle": (
        "Admin/legal fields, children, version history, and governed restructuring for one unit.",
        "एक यूनिट के लिए Admin/legal फ़ील्ड, children, version history, और governed restructuring।",
        "एका युनिटसाठी Admin/legal फील्ड्स, children, version history, आणि governed restructuring.",
        "Ek unit ke Admin/legal fields, children, version history, aur governed restructuring.",
    ),
    "org-unit-detail.body.0": (
        "Full detail view for a single organisation unit — its type, parent, and members.",
        "एक single organisation unit का पूरा detail view — इसका type, parent, और members।",
        "एका organisation unit चे संपूर्ण detail view — त्याचा type, parent, आणि members.",
        "Ek single organisation unit ka pura detail view — uska type, parent, aur members.",
    ),
    "org-unit-detail.body.1": (
        "Name, level, and parent are locked on the Overview tab — those changes must go through Restructure, which closes the current version and opens a new dated one instead of overwriting it.",
        "Name, level, और parent, Overview tab पर locked रहते हैं — इन बदलावों के लिए Restructure से गुज़रना ज़रूरी है, जो current version को बंद करके overwrite करने के बजाय एक नया dated version खोलता है।",
        "Name, level, आणि parent Overview tab वर locked असतात — या बदलांसाठी Restructure मधून जावे लागते, जे current version बंद करून overwrite करण्याऐवजी नवीन dated version उघडते.",
        "Name, level, aur parent Overview tab par locked hote hain — in changes ke liye Restructure se guzarna padta hai, jo current version ko close karke overwrite karne ke bajaye ek naya dated version open karta hai.",
    ),
    "org-unit-detail.stepsHeading": (
        "How a restructure is recorded",
        "Restructure कैसे रिकॉर्ड होता है",
        "Restructure कसे रेकॉर्ड होते",
        "Restructure kaise record hota hai",
    ),
    "org-unit-detail.steps.0.label": ("Choose Change", "Change चुनें", "Change निवडा", "Change Choose karein"),
    "org-unit-detail.steps.0.caption": (
        "Pick a change type — rename, move, merge, split, dissolve, or create.",
        "एक change type चुनें — rename, move, merge, split, dissolve, या create।",
        "एक change type निवडा — rename, move, merge, split, dissolve, किंवा create.",
        "Ek change type pick karein — rename, move, merge, split, dissolve, ya create.",
    ),
    "org-unit-detail.steps.1.label": ("Justify", "Justify करें", "Justify करा", "Justify karein"),
    "org-unit-detail.steps.1.caption": (
        "State the reason and downstream impact — justification is mandatory and feeds the audit trail.",
        "कारण और downstream impact बताएं — justification mandatory है और audit trail में दर्ज होता है।",
        "कारण आणि downstream impact सांगा — justification mandatory आहे आणि audit trail मध्ये नोंदवले जाते.",
        "Reason aur downstream impact batayein — justification mandatory hai aur audit trail mein feed hota hai.",
    ),
    "org-unit-detail.steps.2.label": ("Apply", "Apply करें", "Apply करा", "Apply karein"),
    "org-unit-detail.steps.2.caption": (
        "Submits the change; requires ou:admin permission or it's blocked.",
        "यह change submit करता है; इसके लिए ou:admin permission ज़रूरी है, वरना यह block हो जाता है।",
        "हे change submit करते; यासाठी ou:admin permission आवश्यक आहे, अन्यथा ते block होते.",
        "Ye change submit karta hai; iske liye ou:admin permission chahiye, warna ye block ho jaata hai.",
    ),
    "org-unit-detail.steps.3.label": ("New Version", "नया Version", "नवीन Version", "New Version"),
    "org-unit-detail.steps.3.caption": (
        "The old version closes (Effective To set) and a new one opens, visible in History.",
        "पुराना version बंद हो जाता है (Effective To set होता है) और एक नया version खुलता है, जो History में दिखता है।",
        "जुने version बंद होते (Effective To सेट होते) आणि नवीन version उघडते, जे History मध्ये दिसते.",
        "Purana version close ho jaata hai (Effective To set hota hai) aur ek naya version open hota hai, jo History mein dikhta hai.",
    ),
    "org-unit-detail.fieldRules.0.name": ("New Name", "नया Name", "नवीन Name", "New Name"),
    "org-unit-detail.fieldRules.0.description": (
        "The unit's name going forward — mandatory to apply a restructure.",
        "आगे के लिए यूनिट का name — restructure apply करने के लिए mandatory है।",
        "यापुढील युनिटचे name — restructure apply करण्यासाठी mandatory आहे.",
        "Unit ka aage ka naya name — restructure apply karne ke liye mandatory hai.",
    ),
    "org-unit-detail.fieldRules.1.name": ("New Level", "नया Level", "नवीन Level", "New Level"),
    "org-unit-detail.fieldRules.1.description": (
        "Its position/type in the hierarchy (e.g. department, division) — mandatory.",
        "hierarchy में इसकी position/type (जैसे department, division) — mandatory।",
        "hierarchy मधील त्याची position/type (उदा. department, division) — mandatory.",
        "Hierarchy mein iski position/type (jaise department, division) — mandatory hai.",
    ),
    "org-unit-detail.fieldRules.2.name": ("Change Type", "Change Type", "Change Type", "Change Type"),
    "org-unit-detail.fieldRules.2.description": (
        "Classifies the restructure as create, rename, move, merge, split, or dissolve; recorded against the new version.",
        "Restructure को create, rename, move, merge, split, या dissolve के रूप में classify करता है; नए version के विरुद्ध रिकॉर्ड होता है।",
        "Restructure ला create, rename, move, merge, split, किंवा dissolve म्हणून classify करते; नव्या version विरुद्ध रेकॉर्ड होते.",
        "Restructure ko create, rename, move, merge, split, ya dissolve ke roop mein classify karta hai; naye version ke against record hota hai.",
    ),
    "org-unit-detail.fieldRules.3.name": ("Justification", "Justification", "Justification", "Justification"),
    "org-unit-detail.fieldRules.3.description": (
        "Free-text reason for the change — required for every restructure, kept for audit.",
        "बदलाव के लिए free-text reason — हर restructure के लिए required है, audit के लिए रखा जाता है।",
        "बदलासाठी free-text reason — प्रत्येक restructure साठी required आहे, audit साठी ठेवले जाते.",
        "Change ke liye free-text reason — har restructure ke liye required hai, audit ke liye rakha jaata hai.",
    ),
    "org-unit-detail.fieldRules.4.name": ("New Parent", "नया Parent", "नवीन Parent", "New Parent"),
    "org-unit-detail.fieldRules.4.description": (
        "Reparents the unit; optional — leave blank to make it top-level.",
        "यूनिट को reparent करता है; optional है — top-level बनाने के लिए इसे blank छोड़ें।",
        "युनिटला reparent करते; optional आहे — top-level बनवण्यासाठी हे blank ठेवा.",
        "Unit ko reparent karta hai; optional hai — top-level banane ke liye blank chhod dein.",
    ),
    "org-unit-detail.tip.title": (
        "No cycles possible",
        "Cycle संभव नहीं",
        "Cycle शक्य नाही",
        "Cycle possible nahi hai",
    ),
    "org-unit-detail.tip.body": (
        "The New Parent list hides the unit itself and its entire descendant subtree, so you can't accidentally re-parent a unit under its own child.",
        "New Parent list में यूनिट खुद और उसका पूरा descendant subtree छिपा दिया जाता है, ताकि आप गलती से किसी यूनिट को उसी के child के अंदर re-parent न कर सकें।",
        "New Parent list मध्ये युनिट स्वतः आणि त्याचे संपूर्ण descendant subtree लपवले जाते, जेणेकरून तुम्ही चुकून एखाद्या युनिटला त्याच्याच child खाली re-parent करू शकणार नाही.",
        "New Parent list mein unit khud aur uska pura descendant subtree hide ho jaata hai, taaki aap galti se kisi unit ko uske apne child ke andar re-parent na kar payein.",
    ),
}


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_UNIT_DETAIL.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_UNIT_DETAIL)} org-unit-detail keys.")


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