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

Usage: docker compose exec api python seed_translations_pageinfo_asset_portfolio.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_PORTFOLIO = {
    "asset-portfolio.title": (
        "Asset Portfolio",
        "एसेट पोर्टफोलियो",
        "एसेट पोर्टफोलियो",
        "Asset Portfolio",
    ),
    "asset-portfolio.subtitle": (
        "How to read and drill into the enterprise asset ledger",
        "एंटरप्राइज़ asset ledger को कैसे पढ़ें और उसमें गहराई से जाएं",
        "एंटरप्राइझ asset ledger कसे वाचावे आणि त्यात सखोल जावे",
        "Enterprise asset ledger ko kaise padhein aur usme drill down karein",
    ),
    "asset-portfolio.body.0": (
        "A read-only, filterable ledger of registered assets — category, age, lifecycle state, criticality tier and acquisition cost — pulled live from the same asset records used across the app.",
        "पंजीकृत assets का एक read-only, filterable ledger — category, age, lifecycle state, criticality tier और acquisition cost — जो पूरे app में इस्तेमाल होने वाले उन्हीं asset records से लाइव खींचा जाता है।",
        "नोंदणीकृत assets चे एक read-only, filterable ledger — category, age, lifecycle state, criticality tier आणि acquisition cost — जे संपूर्ण app मध्ये वापरल्या जाणाऱ्या त्याच asset records मधून थेट (live) घेतले जाते.",
        "Registered assets ka ek read-only, filterable ledger — category, age, lifecycle state, criticality tier aur acquisition cost — jo poore app mein use hone wale usi asset records se live pull hota hai.",
    ),
    "asset-portfolio.body.1": (
        "Selections here feed the TCO and NPV & Yield planning workspaces for deeper investment analysis.",
        "यहाँ की selections गहन investment analysis के लिए TCO और NPV & Yield planning workspaces को data भेजती हैं।",
        "येथील selections सखोल investment analysis साठी TCO आणि NPV & Yield planning workspaces मध्ये पाठवल्या जातात.",
        "Yahan ki selections deeper investment analysis ke liye TCO aur NPV & Yield planning workspaces mein feed hoti hain.",
    ),
    "asset-portfolio.stepsHeading": (
        "How to work the portfolio",
        "पोर्टफोलियो पर कैसे काम करें",
        "पोर्टफोलियोवर कसे काम करावे",
        "Portfolio par kaise kaam karein",
    ),
    "asset-portfolio.steps.0.label": ("Filter", "फ़िल्टर करें", "फिल्टर करा", "Filter"),
    "asset-portfolio.steps.0.caption": (
        "Narrow by category / criticality",
        "category / criticality के अनुसार सीमित करें",
        "category / criticality नुसार मर्यादित करा",
        "Category / criticality ke hisaab se narrow karein",
    ),
    "asset-portfolio.steps.1.label": ("Review Roster", "रोस्टर की समीक्षा करें", "रोस्टरचा आढावा घ्या", "Roster review karein"),
    "asset-portfolio.steps.1.caption": (
        "Scan age, state, cost",
        "age, state, cost देखें",
        "age, state, cost पहा",
        "Age, state, cost scan karein",
    ),
    "asset-portfolio.steps.2.label": ("Inspect", "जाँचें", "तपासा", "Inspect karein"),
    "asset-portfolio.steps.2.caption": (
        "Open a Ledger Entry",
        "एक Ledger Entry खोलें",
        "एक Ledger Entry उघडा",
        "Ek Ledger Entry open karein",
    ),
    "asset-portfolio.steps.3.label": ("Analyze", "विश्लेषण करें", "विश्लेषण करा", "Analyze karein"),
    "asset-portfolio.steps.3.caption": (
        "Send to TCO / NPV",
        "TCO / NPV को भेजें",
        "TCO / NPV कडे पाठवा",
        "TCO / NPV mein send karein",
    ),
    "asset-portfolio.fieldRules.0.name": ("Asset Ref", "Asset Ref", "Asset Ref", "Asset Ref"),
    "asset-portfolio.fieldRules.0.description": (
        "System-assigned identifier; opening the row's eye icon shows its full ledger entry.",
        "सिस्टम द्वारा दिया गया identifier; row के eye icon को खोलने पर उसकी पूरी ledger entry दिखती है।",
        "system ने दिलेला identifier; row चे eye icon उघडल्यास त्याची संपूर्ण ledger entry दिसते.",
        "System-assigned identifier hai; row ka eye icon open karne par uski poori ledger entry dikhti hai.",
    ),
    "asset-portfolio.fieldRules.1.name": ("Age", "आयु", "वय", "Age"),
    "asset-portfolio.fieldRules.1.description": (
        "Computed client-side from the acquisition date in years; shows — when no acquisition date is recorded.",
        "acquisition date से वर्षों में client-side पर calculate की जाती है; कोई acquisition date दर्ज न होने पर — दिखाता है।",
        "acquisition date पासून वर्षांमध्ये client-side वर मोजली जाते; कोणतीही acquisition date नोंदवलेली नसल्यास — दाखवते.",
        "Acquisition date se years mein client-side par compute hoti hai; agar acquisition date record na ho to — dikhata hai.",
    ),
    "asset-portfolio.fieldRules.2.name": ("Lifecycle State", "Lifecycle State", "Lifecycle State", "Lifecycle State"),
    "asset-portfolio.fieldRules.2.description": (
        "Current asset lifecycle status (e.g. active, in repair, retired) as set by the asset record.",
        "asset record में सेट किया गया current asset lifecycle status (जैसे active, in repair, retired)।",
        "asset record मध्ये सेट केलेला current asset lifecycle status (उदा. active, in repair, retired).",
        "Asset record mein set kiya gaya current asset lifecycle status (jaise active, in repair, retired).",
    ),
    "asset-portfolio.fieldRules.3.name": ("Criticality", "Criticality", "Criticality", "Criticality"),
    "asset-portfolio.fieldRules.3.description": (
        "Tier derived from the numeric criticality score: 5+ Critical, 4+ High, 3+ Medium, else Low.",
        "numeric criticality score से निकाला गया tier: 5+ Critical, 4+ High, 3+ Medium, अन्यथा Low।",
        "numeric criticality score वरून काढलेला tier: 5+ Critical, 4+ High, 3+ Medium, अन्यथा Low.",
        "Numeric criticality score se derive kiya gaya tier: 5+ Critical, 4+ High, 3+ Medium, warna Low.",
    ),
    "asset-portfolio.fieldRules.4.name": ("Acquisition Cost", "Acquisition Cost", "Acquisition Cost", "Acquisition Cost"),
    "asset-portfolio.fieldRules.4.description": (
        "Purchase cost; filtered rows sum into the Total Acquisition Cost tile above.",
        "खरीद लागत; filtered rows ऊपर दिए गए Total Acquisition Cost tile में जुड़ जाती हैं।",
        "खरेदी किंमत; filtered rows वरील Total Acquisition Cost tile मध्ये बेरीज होतात.",
        "Purchase cost hai; filtered rows upar wale Total Acquisition Cost tile mein sum ho jaati hain.",
    ),
    "asset-portfolio.tip.title": (
        "Critical count vs. roster count",
        "Critical count बनाम roster count",
        "Critical count विरुद्ध roster count",
        "Critical count vs. roster count",
    ),
    "asset-portfolio.tip.body": (
        "The Critical Assets tile is a true portfolio-wide count fetched separately. The roster table and Total Acquisition Cost below it are capped to the first 200 assets, so once the portfolio grows past 200, the table and cost total no longer represent every asset — only the Critical Assets tile does.",
        "Critical Assets tile एक सही मायने में पूरे portfolio का count है जो अलग से fetch किया जाता है। roster table और उसके नीचे का Total Acquisition Cost पहले 200 assets तक सीमित हैं, इसलिए portfolio के 200 से आगे बढ़ने पर table और cost total हर asset को दर्शाना बंद कर देते हैं — केवल Critical Assets tile ही ऐसा करता है।",
        "Critical Assets tile हे संपूर्ण portfolio चे खरे count आहे जे स्वतंत्रपणे fetch केले जाते. roster table आणि त्याखालील Total Acquisition Cost पहिल्या 200 assets पर्यंत मर्यादित आहेत, त्यामुळे portfolio 200 पेक्षा जास्त वाढल्यावर table आणि cost total प्रत्येक asset दर्शवत नाहीत — फक्त Critical Assets tile दर्शवते.",
        "Critical Assets tile ek asli portfolio-wide count hai jo alag se fetch hota hai. Roster table aur uske neeche ka Total Acquisition Cost pehle 200 assets tak capped hain, isliye jaise hi portfolio 200 se aage badhta hai, table aur cost total har asset ko represent nahi karte — sirf Critical Assets tile karta 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 ASSET_PORTFOLIO.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_PORTFOLIO)} asset-portfolio keys.")


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