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

Usage: docker compose exec api python seed_translations_pageinfo_po_wise_asset_report.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)
PO_WISE_ASSET_REPORT = {
    "po-wise-asset-report.title": (
        "PO-wise Asset Report",
        "PO-वार Asset रिपोर्ट",
        "PO-निहाय Asset अहवाल",
        "PO-wise Asset Report",
    ),
    "po-wise-asset-report.subtitle": (
        "Every asset traced back to the Purchase Order that bought it",
        "हर asset को उस Purchase Order तक वापस ट्रेस किया गया है जिसने उसे खरीदा",
        "प्रत्येक asset ला तो विकत घेणाऱ्या Purchase Order पर्यंत परत ट्रेस केले आहे",
        "Har asset ko us Purchase Order tak trace kiya gaya hai jisne use khareeda",
    ),
    "po-wise-asset-report.body.0": (
        "Pick a Purchase Order to see every asset purchased under it — current lifecycle state, current custodian, and export.",
        "किसी Purchase Order को चुनें ताकि उसके अंतर्गत खरीदा गया हर asset दिखे — current lifecycle state, current custodian, और export।",
        "एखादी Purchase Order निवडा जेणेकरून तिच्याअंतर्गत खरेदी केलेली प्रत्येक asset दिसेल — current lifecycle state, current custodian, आणि export.",
        "Ek Purchase Order select karein taaki uske under khareedi gayi har asset dikhe — current lifecycle state, current custodian, aur export.",
    ),
    "po-wise-asset-report.body.1": (
        "Useful for reconciling procurement spend against what was actually delivered and where those assets stand today.",
        "यह procurement खर्च का मिलान इस बात से करने में उपयोगी है कि वास्तव में क्या डिलीवर हुआ और वे assets आज कहाँ हैं।",
        "प्रत्यक्षात काय डिलिव्हर झाले आणि त्या assets आज कुठे आहेत याच्याशी procurement खर्चाचा ताळमेळ घालण्यासाठी हे उपयुक्त आहे.",
        "Procurement spend ko reconcile karne ke liye useful hai ki actually kya deliver hua aur wo assets aaj kahaan stand karte hain.",
    ),
    "po-wise-asset-report.stepsHeading": (
        "How this report works",
        "यह रिपोर्ट कैसे काम करती है",
        "हा अहवाल कसा कार्य करतो",
        "Ye report kaise kaam karti hai",
    ),
    "po-wise-asset-report.steps.0.label": ("Select PO", "PO चुनें", "PO निवडा", "PO Select Karein"),
    "po-wise-asset-report.steps.0.caption": (
        "Choose a Purchase Order from the dropdown.",
        "dropdown से एक Purchase Order चुनें।",
        "dropdown मधून एक Purchase Order निवडा.",
        "Dropdown se ek Purchase Order choose karein.",
    ),
    "po-wise-asset-report.steps.1.label": ("Report Loads", "रिपोर्ट लोड होती है", "अहवाल लोड होतो", "Report Load Hoti Hai"),
    "po-wise-asset-report.steps.1.caption": (
        "Asset count and total acquisition cost are fetched for that PO.",
        "उस PO के लिए asset count और total acquisition cost फ़ेच किए जाते हैं।",
        "त्या PO साठी asset count आणि total acquisition cost फेच केले जातात.",
        "Us PO ke liye asset count aur total acquisition cost fetch kiye jaate hain.",
    ),
    "po-wise-asset-report.steps.2.label": ("Review Assets", "Assets की समीक्षा करें", "Assets चे पुनरावलोकन करा", "Assets Review Karein"),
    "po-wise-asset-report.steps.2.caption": (
        "Table lists every asset created against this PO with its lifecycle state and custodian.",
        "Table में इस PO के विरुद्ध बनाए गए हर asset को उसकी lifecycle state और custodian के साथ सूचीबद्ध किया गया है।",
        "Table मध्ये या PO विरुद्ध तयार केलेली प्रत्येक asset तिच्या lifecycle state आणि custodian सह सूचीबद्ध केली आहे.",
        "Table mein is PO ke against banayi gayi har asset uski lifecycle state aur custodian ke saath list hoti hai.",
    ),
    "po-wise-asset-report.steps.3.label": ("Export", "Export करें", "Export करा", "Export Karein"),
    "po-wise-asset-report.steps.3.caption": (
        "Download the table for records or audit.",
        "records या audit के लिए table डाउनलोड करें।",
        "records किंवा audit साठी table डाउनलोड करा.",
        "Records ya audit ke liye table download karein.",
    ),
    "po-wise-asset-report.fieldRules.0.name": ("Purchase Order", "Purchase Order", "Purchase Order", "Purchase Order"),
    "po-wise-asset-report.fieldRules.0.description": (
        "Selecting a PO triggers the report fetch; the report stays empty until one is chosen.",
        "PO चुनने से report fetch ट्रिगर होता है; जब तक कोई नहीं चुना जाता, report खाली रहती है।",
        "PO निवडल्याने report fetch ट्रिगर होतो; जोपर्यंत एखादी निवडली जात नाही तोपर्यंत report रिकामा राहतो.",
        "PO select karne se report fetch trigger hota hai; jab tak koi choose nahi hota, report empty rehti hai.",
    ),
    "po-wise-asset-report.fieldRules.1.name": ("Lifecycle State", "Lifecycle State", "Lifecycle State", "Lifecycle State"),
    "po-wise-asset-report.fieldRules.1.description": (
        "The asset's current status (e.g. Active, Disposed) — not its status at the time of purchase.",
        "asset की current स्थिति (जैसे Active, Disposed) — खरीद के समय की स्थिति नहीं।",
        "asset ची current स्थिती (उदा. Active, Disposed) — खरेदीच्या वेळची स्थिती नाही.",
        "Asset ki current status (jaise Active, Disposed) — purchase ke time ki status nahi.",
    ),
    "po-wise-asset-report.fieldRules.2.name": ("Current Custodian", "वर्तमान Custodian", "सद्य Custodian", "Current Custodian"),
    "po-wise-asset-report.fieldRules.2.description": (
        "The asset's present custodian, which may differ from whoever originally received it under this PO.",
        "asset का वर्तमान custodian, जो इस PO के तहत मूल रूप से इसे प्राप्त करने वाले व्यक्ति से भिन्न हो सकता है।",
        "asset चा सध्याचा custodian, जो या PO अंतर्गत मूळतः तो प्राप्त करणाऱ्या व्यक्तीपेक्षा वेगळा असू शकतो.",
        "Asset ka present custodian, jo is PO ke under originally ise receive karne wale se different ho sakta hai.",
    ),
    "po-wise-asset-report.fieldRules.3.name": ("Acquisition Cost", "Acquisition Cost", "Acquisition Cost", "Acquisition Cost"),
    "po-wise-asset-report.fieldRules.3.description": (
        "Unit cost recorded on the asset; summed into the header card's Total Acquisition Cost.",
        "asset पर दर्ज unit cost; इसे header card के Total Acquisition Cost में जोड़ा जाता है।",
        "asset वर नोंदवलेला unit cost; तो header card च्या Total Acquisition Cost मध्ये बेरीज केला जातो.",
        "Asset par record ki gayi unit cost; ise header card ke Total Acquisition Cost mein sum kiya jaata hai.",
    ),
    "po-wise-asset-report.tip.title": (
        "Rows show today's state, not PO-time state",
        "Rows आज की स्थिति दिखाते हैं, PO के समय की नहीं",
        "Rows आजची स्थिती दाखवतात, PO च्या वेळची नाही",
        "Rows aaj ki state dikhate hain, PO-time ki nahi",
    ),
    "po-wise-asset-report.tip.body": (
        "Lifecycle State and Current Custodian are live values. An asset later transferred or disposed still appears under this PO, but with its current status and holder — not what it was when it was first linked to the PO.",
        "Lifecycle State और Current Custodian live values हैं। बाद में transfer या dispose की गई asset अब भी इस PO के तहत दिखती है, लेकिन अपनी current status और holder के साथ — न कि उस समय की स्थिति जब यह पहली बार PO से जुड़ी थी।",
        "Lifecycle State आणि Current Custodian या live values आहेत. नंतर transfer किंवा dispose केलेली asset अजूनही या PO अंतर्गत दिसते, पण तिच्या current status आणि holder सह — PO शी प्रथम जोडली गेली तेव्हाची स्थिती नव्हे.",
        "Lifecycle State aur Current Custodian live values hain. Baad mein transfer ya dispose hui asset ab bhi is PO ke under dikhti hai, lekin apni current status aur holder ke saath — na ki jab wo pehli baar PO se link hui thi tab ki state.",
    ),
}


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 PO_WISE_ASSET_REPORT.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(PO_WISE_ASSET_REPORT)} po-wise-asset-report keys.")


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