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

Usage: docker compose exec api python seed_translations_pageinfo_create_grn.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)
CREATE_GRN = {
    "create-grn.title": (
        "Goods Receipt Note",
        "गुड्स रिसीट नोट (GRN)",
        "गुड्स रिसीट नोट (GRN)",
        "Goods Receipt Note (GRN)",
    ),
    "create-grn.subtitle": (
        "Record what actually arrived against an open PO, line by line.",
        "किसी open PO के विरुद्ध वास्तव में क्या पहुँचा, यह लाइन-दर-लाइन दर्ज करें।",
        "एखाद्या open PO विरुद्ध प्रत्यक्षात काय पोहोचले, हे ओळीनुसार नोंदवा.",
        "Ek open PO ke against actually kya aaya, wo line-by-line record karein.",
    ),
    "create-grn.body.0": (
        "A GRN captures the real delivery against a purchase order — ordered vs. received vs. accepted quantity per item — so short-shipments or rejected goods are on record before the vendor invoice is verified.",
        "GRN किसी purchase order के विरुद्ध हुई वास्तविक डिलीवरी दर्ज करता है — प्रत्येक item के लिए ordered बनाम received बनाम accepted मात्रा — ताकि vendor invoice verify होने से पहले ही short-shipment या reject किए गए सामान का रिकॉर्ड मौजूद रहे।",
        "GRN एखाद्या purchase order विरुद्ध झालेली प्रत्यक्ष delivery नोंदवते — प्रत्येक item साठी ordered विरुद्ध received विरुद्ध accepted प्रमाण — जेणेकरून vendor invoice verify होण्यापूर्वीच short-shipment किंवा reject केलेल्या मालाची नोंद राहील.",
        "GRN kisi purchase order ke against hui actual delivery record karta hai — har item ke liye ordered vs received vs accepted quantity — taaki vendor invoice verify hone se pehle hi short-shipments ya reject hue goods ka record ban jaaye.",
    ),
    "create-grn.body.1": (
        "Opening this page from a PO's \"Create GRN\" action pre-selects that PO; otherwise it defaults to the first open PO.",
        "किसी PO के \"Create GRN\" action से यह पेज खोलने पर वह PO पहले से चुना हुआ होता है; अन्यथा यह डिफ़ॉल्ट रूप से पहले open PO को चुनता है।",
        "एखाद्या PO च्या \"Create GRN\" action मधून हे पेज उघडल्यास तो PO आधीच निवडलेला असतो; अन्यथा ते डीफॉल्टनुसार पहिल्या open PO ला निवडते.",
        "Kisi PO ke \"Create GRN\" action se ye page open karne par wo PO already pre-selected hota hai; warna ye default first open PO select kar leta hai.",
    ),
    "create-grn.stepsHeading": (
        "How a GRN is recorded",
        "GRN कैसे दर्ज किया जाता है",
        "GRN कसे नोंदवले जाते",
        "GRN kaise record hota hai",
    ),
    "create-grn.steps.0.label": ("Select PO", "PO चुनें", "PO निवडा", "PO select karein"),
    "create-grn.steps.0.caption": (
        "Pick the open purchase order the goods arrived against.",
        "वह open purchase order चुनें जिसके विरुद्ध सामान पहुँचा है।",
        "ज्या open purchase order विरुद्ध माल पोहोचला आहे तो निवडा.",
        "Wo open purchase order pick karein jiske against goods aaya hai.",
    ),
    "create-grn.steps.1.label": ("Enter receipt", "रसीद दर्ज करें", "पावती नोंदवा", "Receipt enter karein"),
    "create-grn.steps.1.caption": (
        "Set received date, remarks, and an optional DC file.",
        "received date, remarks, और वैकल्पिक DC file सेट करें।",
        "received date, remarks आणि पर्यायी DC file सेट करा.",
        "Received date, remarks, aur ek optional DC file set karein.",
    ),
    "create-grn.steps.2.label": ("Adjust quantities", "मात्राएँ समायोजित करें", "प्रमाण समायोजित करा", "Quantities adjust karein"),
    "create-grn.steps.2.caption": (
        "Edit received/accepted per line item; defaults to ordered qty.",
        "प्रत्येक line item के लिए received/accepted संपादित करें; डिफ़ॉल्ट रूप से यह ordered qty होती है।",
        "प्रत्येक line item साठी received/accepted संपादित करा; डीफॉल्टनुसार ते ordered qty असते.",
        "Har line item ke liye received/accepted edit karein; default ordered qty hoti hai.",
    ),
    "create-grn.steps.3.label": ("Create GRN", "GRN बनाएँ", "GRN तयार करा", "GRN create karein"),
    "create-grn.steps.3.caption": (
        "Submits the receipt; the DC file uploads right after.",
        "यह receipt सबमिट करता है; उसके तुरंत बाद DC file अपलोड होती है।",
        "हे receipt सबमिट करते; त्यानंतर लगेच DC file अपलोड होते.",
        "Ye receipt submit karta hai; uske turant baad DC file upload hoti hai.",
    ),
    "create-grn.steps.4.label": ("Verify invoice", "इनवॉइस सत्यापित करें", "इनव्हॉइस पडताळा", "Invoice verify karein"),
    "create-grn.steps.4.caption": (
        "Jump straight to Invoice Verification for this PO/GRN.",
        "इस PO/GRN के लिए सीधे Invoice Verification पर जाएँ।",
        "या PO/GRN साठी थेट Invoice Verification वर जा.",
        "Is PO/GRN ke liye seedha Invoice Verification par jump karein.",
    ),
    "create-grn.fieldRules.0.name": ("Purchase Order", "परचेज़ ऑर्डर", "परचेज़ ऑर्डर", "Purchase Order"),
    "create-grn.fieldRules.0.description": (
        "Only open POs are listed; this drives which line items appear below.",
        "केवल open PO ही सूचीबद्ध होते हैं; यही तय करता है कि नीचे कौन-से line items दिखेंगे।",
        "फक्त open PO सूचीबद्ध केले जातात; हेच ठरवते की खाली कोणते line items दिसतील.",
        "Sirf open POs hi list hote hain; yahi decide karta hai ki neeche kaunse line items dikhenge.",
    ),
    "create-grn.fieldRules.1.name": ("Received Date", "प्राप्ति तिथि", "प्राप्ती तारीख", "Received Date"),
    "create-grn.fieldRules.1.description": (
        "Defaults to today; recorded as the GRN's receipt date.",
        "डिफ़ॉल्ट रूप से आज की तारीख होती है; इसे GRN की receipt date के रूप में दर्ज किया जाता है।",
        "डीफॉल्टनुसार आजची तारीख असते; ती GRN ची receipt date म्हणून नोंदवली जाते.",
        "Default aaj ki date hoti hai; isi ko GRN ki receipt date ke roop mein record kiya jaata hai.",
    ),
    "create-grn.fieldRules.2.name": ("Received / Accepted Qty", "प्राप्त / स्वीकृत मात्रा", "प्राप्त / स्वीकृत प्रमाण", "Received / Accepted Qty"),
    "create-grn.fieldRules.2.description": (
        "Per line item, defaults to ordered qty — lower it to log short-receipts or rejections.",
        "प्रत्येक line item के लिए, डिफ़ॉल्ट रूप से यह ordered qty होती है — short-receipt या rejection दर्ज करने के लिए इसे घटाएँ।",
        "प्रत्येक line item साठी, डीफॉल्टनुसार ती ordered qty असते — short-receipt किंवा rejection नोंदवण्यासाठी ती कमी करा.",
        "Har line item ke liye, default ordered qty hoti hai — short-receipts ya rejections log karne ke liye ise kam karein.",
    ),
    "create-grn.fieldRules.3.name": ("DC File", "DC File", "DC File", "DC File"),
    "create-grn.fieldRules.3.description": (
        "Optional delivery challan scan/photo; uploaded only after the GRN itself is created.",
        "वैकल्पिक delivery challan scan/photo; यह तभी अपलोड होता है जब GRN खुद बन चुका हो।",
        "पर्यायी delivery challan scan/photo; हे तेव्हाच अपलोड होते जेव्हा GRN स्वतः तयार झालेली असते.",
        "Optional delivery challan scan/photo; ye tabhi upload hota hai jab GRN khud create ho chuka ho.",
    ),
    "create-grn.tip.title": (
        "GRN can succeed even if the file doesn't",
        "फ़ाइल असफल होने पर भी GRN सफल हो सकता है",
        "फाइल अयशस्वी झाली तरीही GRN यशस्वी होऊ शकते",
        "File fail ho jaaye tab bhi GRN succeed ho sakta hai",
    ),
    "create-grn.tip.body": (
        "The GRN record is created first, then the DC file is uploaded against it. If the upload fails, you still get a valid GRN — just re-open it later to attach the file instead of resubmitting the whole receipt.",
        "पहले GRN record बनाया जाता है, फिर उसके विरुद्ध DC file अपलोड होती है। यदि upload विफल हो जाए, तो भी आपको एक valid GRN मिल जाता है — पूरी receipt दोबारा सबमिट करने के बजाय बाद में इसे दोबारा खोलकर बस file अटैच कर दें।",
        "आधी GRN record तयार केला जातो, त्यानंतर त्याविरुद्ध DC file अपलोड होते. जर upload अयशस्वी झाले, तरीही तुम्हाला एक valid GRN मिळतो — संपूर्ण receipt पुन्हा सबमिट करण्याऐवजी नंतर तो पुन्हा उघडून फक्त file attach करा.",
        "Pehle GRN record create hota hai, uske baad uske against DC file upload hoti hai. Agar upload fail ho jaaye, tab bhi aapko ek valid GRN mil jaata hai — poori receipt dobara submit karne ke bajaye baad mein use re-open karke bas file attach kar dein.",
    ),
}


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 CREATE_GRN.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(CREATE_GRN)} create-grn keys.")


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