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

Usage: docker compose exec api python seed_translations_pageinfo_goods_receipt_register.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)
GOODS_RECEIPT_REGISTER = {
    "goods-receipt-register.title": (
        "Goods Receipt Register",
        "गुड्स रिसीट रजिस्टर",
        "गुड्स रिसीट रजिस्टर",
        "Goods Receipt Register",
    ),
    "goods-receipt-register.subtitle": (
        "Log of every stock-in transaction",
        "प्रत्येक स्टॉक-इन ट्रांज़ैक्शन का लॉग",
        "प्रत्येक स्टॉक-इन ट्रान्झॅक्शनचा लॉग",
        "Har stock-in transaction ka log",
    ),
    "goods-receipt-register.body.0": (
        "Every time stock is received — from a vendor shipment, a PO delivery, or any other source — it's recorded here as a stock-in transaction against an item.",
        "जब भी स्टॉक प्राप्त होता है — किसी vendor shipment, PO delivery, या किसी अन्य स्रोत से — इसे यहाँ किसी item के विरुद्ध stock-in transaction के रूप में दर्ज किया जाता है।",
        "जेव्हा जेव्हा स्टॉक प्राप्त होतो — एखाद्या vendor shipment, PO delivery, किंवा इतर कोणत्याही स्रोतातून — तो येथे एखाद्या item विरुद्ध stock-in transaction म्हणून नोंदवला जातो.",
        "Jab bhi stock receive hota hai — kisi vendor shipment, PO delivery, ya kisi aur source se — use yahan ek item ke against stock-in transaction ke roop mein record kiya jaata hai.",
    ),
    "goods-receipt-register.body.1": (
        "This is a flat log, not an approval workflow: recording a receipt immediately increases that item's quantity on hand. There's no separate QC or acceptance step.",
        "यह एक flat log है, कोई approval workflow नहीं: receipt दर्ज करते ही उस item की quantity on hand तुरंत बढ़ जाती है। इसमें कोई अलग QC या acceptance step नहीं है।",
        "हा एक flat log आहे, approval workflow नाही: receipt नोंदवताच त्या item ची quantity on hand लगेच वाढते. यात वेगळा QC किंवा acceptance step नाही.",
        "Ye ek flat log hai, koi approval workflow nahi: receipt record karte hi us item ki quantity on hand turant badh jaati hai. Isme alag se koi QC ya acceptance step nahi hai.",
    ),
    "goods-receipt-register.stepsHeading": (
        "How a receipt is recorded",
        "receipt कैसे दर्ज किया जाता है",
        "receipt कशी नोंदवली जाते",
        "Receipt kaise record hoti hai",
    ),
    "goods-receipt-register.steps.0.label": ("Select Item", "Item चुनें", "Item निवडा", "Item select karein"),
    "goods-receipt-register.steps.0.caption": (
        "Pick the item that's being received.",
        "वह item चुनें जो प्राप्त किया जा रहा है।",
        "जी item प्राप्त केली जात आहे ती निवडा.",
        "Jo item receive ho rahi hai use pick karein.",
    ),
    "goods-receipt-register.steps.1.label": ("Enter Qty & Cost", "Qty और Cost दर्ज करें", "Qty आणि Cost टाका", "Qty aur Cost enter karein"),
    "goods-receipt-register.steps.1.caption": (
        "Quantity received and its unit cost, plus the location.",
        "प्राप्त quantity और उसकी unit cost, साथ ही location।",
        "प्राप्त झालेली quantity आणि तिची unit cost, तसेच location.",
        "Kitni quantity receive hui aur uski unit cost, saath hi location.",
    ),
    "goods-receipt-register.steps.2.label": ("Attach Receipt", "Receipt अटैच करें", "Receipt अटॅच करा", "Receipt attach karein"),
    "goods-receipt-register.steps.2.caption": (
        "Optionally upload the vendor's invoice or delivery note.",
        "वैकल्पिक रूप से vendor का invoice या delivery note अपलोड करें।",
        "पर्यायाने vendor चे invoice किंवा delivery note अपलोड करा.",
        "Chaho to vendor ka invoice ya delivery note upload kar sakte hain.",
    ),
    "goods-receipt-register.steps.3.label": ("Submit", "सबमिट करें", "सबमिट करा", "Submit karein"),
    "goods-receipt-register.steps.3.caption": (
        "Stock is updated instantly and the transaction is logged.",
        "Stock तुरंत अपडेट हो जाता है और transaction लॉग हो जाता है।",
        "Stock त्वरित अपडेट होतो आणि transaction लॉग होते.",
        "Stock turant update ho jaata hai aur transaction log ho jaata hai.",
    ),
    "goods-receipt-register.fieldRules.0.name": ("Item", "Item", "Item", "Item"),
    "goods-receipt-register.fieldRules.0.description": (
        "Which inventory item's stock-on-hand is increased.",
        "किस inventory item का stock-on-hand बढ़ाया जाता है।",
        "कोणत्या inventory item चा stock-on-hand वाढवला जातो.",
        "Kis inventory item ka stock-on-hand badhaya jaata hai.",
    ),
    "goods-receipt-register.fieldRules.1.name": ("Quantity", "मात्रा", "प्रमाण", "Quantity"),
    "goods-receipt-register.fieldRules.1.description": (
        "Amount received; added directly to the item's stock.",
        "प्राप्त की गई मात्रा; सीधे item के stock में जोड़ी जाती है।",
        "प्राप्त झालेले प्रमाण; थेट item च्या stock मध्ये जोडले जाते.",
        "Jitni quantity receive hui; seedhe item ke stock mein add ho jaati hai.",
    ),
    "goods-receipt-register.fieldRules.2.name": ("Unit Cost", "यूनिट कॉस्ट", "युनिट कॉस्ट", "Unit Cost"),
    "goods-receipt-register.fieldRules.2.description": (
        "Optional, but needed for the Total column and the Total Receipt Value card.",
        "वैकल्पिक है, लेकिन Total column और Total Receipt Value card के लिए ज़रूरी है।",
        "पर्यायी आहे, पण Total column आणि Total Receipt Value card साठी आवश्यक आहे.",
        "Optional hai, lekin Total column aur Total Receipt Value card ke liye zaroori hai.",
    ),
    "goods-receipt-register.fieldRules.3.name": ("Location", "लोकेशन", "लोकेशन", "Location"),
    "goods-receipt-register.fieldRules.3.description": (
        "Where the stock is placed; left unassigned if omitted.",
        "स्टॉक कहाँ रखा गया है; न भरने पर unassigned रहता है।",
        "स्टॉक कुठे ठेवला आहे; न भरल्यास unassigned राहते.",
        "Stock kahan rakha gaya hai; agar chhoda jaaye to unassigned reh jaata hai.",
    ),
    "goods-receipt-register.fieldRules.4.name": ("Receipt File", "रिसीट फ़ाइल", "रिसीट फाइल", "Receipt File"),
    "goods-receipt-register.fieldRules.4.description": (
        "Optional image or PDF proof, viewable later from the Receipt column.",
        "वैकल्पिक image या PDF प्रमाण, जिसे बाद में Receipt column से देखा जा सकता है।",
        "पर्यायी image किंवा PDF पुरावा, जो नंतर Receipt column मधून पाहता येतो.",
        "Optional image ya PDF proof, jo baad mein Receipt column se dekha ja sakta hai.",
    ),
    "goods-receipt-register.tip.title": (
        "Grand total may be partial",
        "Grand total अधूरा हो सकता है",
        "Grand total अपूर्ण असू शकतो",
        "Grand total partial ho sakta hai",
    ),
    "goods-receipt-register.tip.body": (
        "The Total Receipt Value card sums only the first 200 stock-in transactions loaded (this endpoint's page-size cap). If the amber warning under it shows fewer loaded than total, the figure isn't a true grand total — narrow the Year filter to get an exact sum.",
        "Total Receipt Value card केवल पहले load किए गए 200 stock-in transactions को जोड़ता है (यह इस endpoint का page-size cap है)। यदि इसके नीचे दिखने वाली amber warning में loaded की संख्या total से कम है, तो यह आंकड़ा असली grand total नहीं है — सटीक sum पाने के लिए Year filter को संकीर्ण करें।",
        "Total Receipt Value card फक्त पहिल्या load झालेल्या 200 stock-in transactions ची बेरीज करते (हे या endpoint चे page-size cap आहे). जर त्याखालील amber warning मध्ये loaded संख्या total पेक्षा कमी दिसत असेल, तर हा आकडा खरा grand total नाही — अचूक बेरीज मिळवण्यासाठी Year filter संकुचित करा.",
        "Total Receipt Value card sirf pehle load hue 200 stock-in transactions ko sum karta hai (ye is endpoint ka page-size cap hai). Agar niche wali amber warning mein loaded ki count total se kam dikh rahi hai, to ye figure asli grand total nahi hai — exact sum pane ke liye Year filter ko narrow karein.",
    ),
}


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 GOODS_RECEIPT_REGISTER.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(GOODS_RECEIPT_REGISTER)} goods-receipt-register keys.")


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