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

Usage: docker compose exec api python seed_translations_pageinfo_asset_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)
ASSET_DETAIL = {
    "asset-detail.title": (
        "Asset Details",
        "Asset विवरण",
        "Asset तपशील",
        "Asset ki Details",
    ),
    "asset-detail.subtitle": (
        "Single source of truth for one asset",
        "एक asset के लिए सत्य का एकमात्र स्रोत",
        "एका asset साठी सत्याचा एकमेव स्रोत",
        "Ek asset ke liye single source of truth",
    ),
    "asset-detail.body.0": (
        "Full detail view for a single asset — specifications, custody, documents, financials, and history, across tabs.",
        "एक asset के लिए पूर्ण विस्तृत दृश्य — specifications, custody, documents, financials, और history, सभी tabs में।",
        "एका asset साठी संपूर्ण तपशीलवार दृश्य — specifications, custody, documents, financials, आणि history, सर्व tabs मध्ये.",
        "Ek single asset ka poora detail view — specifications, custody, documents, financials, aur history, sabhi tabs mein.",
    ),
    "asset-detail.body.1": (
        "The bar above the tabs shows the asset's current lifecycle state and only lists the transitions actually valid from here — the backend state machine decides what's possible, not the UI.",
        "tabs के ऊपर की bar asset की मौजूदा lifecycle state दिखाती है और यहाँ से वास्तव में valid transitions ही सूचीबद्ध करती है — क्या संभव है यह backend state machine तय करती है, UI नहीं।",
        "tabs च्या वर असलेली bar asset ची सध्याची lifecycle state दाखवते आणि इथून प्रत्यक्षात valid असलेले transitions च सूचीबद्ध करते — काय शक्य आहे हे backend state machine ठरवते, UI नाही.",
        "Tabs ke upar wali bar asset ki current lifecycle state dikhati hai aur sirf wahi transitions list karti hai jo yahan se actually valid hain — kya possible hai ye backend state machine decide karta hai, UI nahi.",
    ),
    "asset-detail.stepsHeading": (
        "Lifecycle at a glance",
        "एक नज़र में Lifecycle",
        "एका दृष्टिक्षेपात Lifecycle",
        "Ek nazar mein Lifecycle",
    ),
    "asset-detail.steps.0.label": ("Draft", "Draft", "Draft", "Draft"),
    "asset-detail.steps.0.caption": (
        "Registered, not yet in service",
        "Registered, अभी service में नहीं",
        "Registered, अजून service मध्ये नाही",
        "Registered hai, abhi service mein nahi aaya",
    ),
    "asset-detail.steps.1.label": ("Pending Commissioning", "Pending Commissioning", "Pending Commissioning", "Pending Commissioning"),
    "asset-detail.steps.1.caption": (
        "Awaiting finance sign-off",
        "Finance sign-off का इंतज़ार",
        "Finance sign-off ची प्रतीक्षा",
        "Finance sign-off ka wait ho raha hai",
    ),
    "asset-detail.steps.2.label": ("Commissioned", "Commissioned", "Commissioned", "Commissioned"),
    "asset-detail.steps.2.caption": (
        "Auto-capitalised, ready for use",
        "Auto-capitalised, उपयोग के लिए तैयार",
        "Auto-capitalised, वापरासाठी तयार",
        "Auto-capitalised ho chuka hai, use ke liye ready",
    ),
    "asset-detail.steps.3.label": ("In Operation", "In Operation", "In Operation", "In Operation"),
    "asset-detail.steps.3.caption": (
        "Active — can transfer, impair, or flag for disposal",
        "Active — transfer, impair किया जा सकता है, या disposal के लिए flag किया जा सकता है।",
        "Active — transfer, impair करता येते, किंवा disposal साठी flag करता येते.",
        "Active hai — transfer, impair kar sakte hain, ya disposal ke liye flag kar sakte hain",
    ),
    "asset-detail.steps.4.label": ("Disposed / Written Off", "Disposed / Written Off", "Disposed / Written Off", "Disposed / Written Off"),
    "asset-detail.steps.4.caption": (
        "Terminal — can only be archived next",
        "Terminal — इसके बाद केवल archive किया जा सकता है।",
        "Terminal — यानंतर फक्त archive करता येते.",
        "Terminal state hai — iske baad sirf archive kiya ja sakta hai",
    ),
    "asset-detail.fieldRules.0.name": ("Lifecycle State", "Lifecycle State", "Lifecycle State", "Lifecycle State"),
    "asset-detail.fieldRules.0.description": (
        "Drives which action buttons and transitions are available; changed only via the state bar above, never edited directly.",
        "यह तय करता है कि कौन-से action buttons और transitions उपलब्ध हैं; इसे केवल ऊपर दी गई state bar के ज़रिए बदला जाता है, कभी सीधे edit नहीं किया जाता।",
        "हे ठरवते की कोणते action buttons आणि transitions उपलब्ध आहेत; हे फक्त वरील state bar द्वारे बदलले जाते, कधीही थेट edit केले जात नाही.",
        "Ye decide karta hai ki kaunse action buttons aur transitions available hain; ise sirf upar wali state bar se change kiya jaata hai, kabhi bhi directly edit nahi kiya jaata",
    ),
    "asset-detail.fieldRules.1.name": ("Custodian", "Custodian", "Custodian", "Custodian"),
    "asset-detail.fieldRules.1.description": (
        "Current responsible person; changed only through Transfer, which requires the receiver to accept.",
        "वर्तमान में ज़िम्मेदार व्यक्ति; इसे केवल Transfer के ज़रिए बदला जाता है, जिसमें receiver को स्वीकार करना ज़रूरी होता है।",
        "सध्या जबाबदार असलेली व्यक्ती; हे फक्त Transfer द्वारे बदलले जाते, ज्यामध्ये receiver ने स्वीकारणे आवश्यक असते.",
        "Abhi jo responsible person hai; ise sirf Transfer ke through change kiya jaata hai, jisme receiver ko accept karna zaroori hota hai",
    ),
    "asset-detail.fieldRules.2.name": ("Acquisition Cost", "Acquisition Cost", "Acquisition Cost", "Acquisition Cost"),
    "asset-detail.fieldRules.2.description": (
        "Feeds depreciation and the Below-Capitalisation-Threshold flag shown in Overview.",
        "यह depreciation में जाता है और Overview में दिखाए गए Below-Capitalisation-Threshold flag को भी प्रभावित करता है।",
        "हे depreciation मध्ये जाते आणि Overview मध्ये दाखवलेल्या Below-Capitalisation-Threshold flag वरही परिणाम करते.",
        "Ye depreciation mein feed hota hai aur Overview mein dikhne wale Below-Capitalisation-Threshold flag ko bhi affect karta hai",
    ),
    "asset-detail.fieldRules.3.name": ("Purchase Order", "Purchase Order", "Purchase Order", "Purchase Order"),
    "asset-detail.fieldRules.3.description": (
        "Only shown when Procurement (M24) is enabled for the tenant; links back to the originating PO.",
        "यह तभी दिखता है जब tenant के लिए Procurement (M24) enabled हो; यह मूल PO से लिंक करता है।",
        "हे फक्त तेव्हाच दिसते जेव्हा tenant साठी Procurement (M24) enabled असते; हे मूळ PO शी लिंक करते.",
        "Ye tab hi dikhta hai jab tenant ke liye Procurement (M24) enabled ho; ye originating PO se link karta hai",
    ),
    "asset-detail.tip.title": (
        "Disposal needs a clear custody trail",
        "Disposal के लिए एक स्पष्ट custody trail ज़रूरी है",
        "Disposal साठी स्पष्ट custody trail आवश्यक आहे",
        "Disposal ke liye clear custody trail zaroori hai",
    ),
    "asset-detail.tip.body": (
        "You can't transition an asset to Pending Disposal or Disposed while it has an active or pending-acceptance custody record — resolve or complete the Custody tab's transfer first, or the transition is rejected.",
        "जब तक asset का कोई active या pending-acceptance custody record मौजूद है, तब तक आप उसे Pending Disposal या Disposed में transition नहीं कर सकते — पहले Custody tab के transfer को resolve या complete करें, वरना transition reject हो जाएगा।",
        "जोपर्यंत asset चा एखादा active किंवा pending-acceptance custody record अस्तित्वात आहे, तोपर्यंत तुम्ही त्याला Pending Disposal किंवा Disposed मध्ये transition करू शकत नाही — आधी Custody tab च्या transfer ला resolve किंवा complete करा, अन्यथा transition reject होईल.",
        "Jab tak asset ka koi active ya pending-acceptance custody record maujood hai, tab tak aap use Pending Disposal ya Disposed mein transition nahi kar sakte — pehle Custody tab ke transfer ko resolve ya complete karein, warna transition reject ho jayega",
    ),
}


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 ASSET_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(ASSET_DETAIL)} asset-detail keys.")


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