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

Usage: docker compose exec api python seed_translations_pageinfo_po_approvals.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_APPROVALS = {
    "po-approvals.title": (
        "PO Approval Queue",
        "PO अप्रूवल क्यू",
        "PO अप्रूव्हल क्यू",
        "PO Approval Queue",
    ),
    "po-approvals.subtitle": (
        "Sign off on purchase orders before they move to goods receipt.",
        "PO को goods receipt में जाने से पहले sign off करें।",
        "PO goods receipt मध्ये जाण्यापूर्वी sign off करा.",
        "Purchase orders ko goods receipt mein jaane se pehle sign off karein.",
    ),
    "po-approvals.body.0": (
        "This queue lists every purchase order with approval_status=pending. Select a PO to see its line items, total, and expected delivery date, then approve or reject it with an optional remark.",
        "यह queue उन सभी purchase orders को सूचीबद्ध करती है जिनका approval_status=pending है। किसी PO को चुनें ताकि उसके line items, total, और expected delivery date दिख सकें, फिर उसे optional remark के साथ approve या reject करें।",
        "या queue मध्ये approval_status=pending असलेले सर्व purchase orders सूचीबद्ध केले जातात. एखादी PO निवडा म्हणजे तिचे line items, total, आणि expected delivery date दिसतील, नंतर ऐच्छिक remark सह ती approve किंवा reject करा.",
        "Ye queue un sabhi purchase orders ko list karti hai jinka approval_status=pending hai. Kisi PO ko select karein taaki uske line items, total, aur expected delivery date dikhein, phir use optional remark ke saath approve ya reject karein.",
    ),
    "po-approvals.body.1": (
        "Maker-checker is enforced server-side: whoever raised the PO cannot approve or reject it themselves, even if they hold approval permission.",
        "Maker-checker सर्वर-साइड पर enforce होता है: जिसने भी PO raise किया है, वह स्वयं उसे approve या reject नहीं कर सकता, भले ही उसके पास approval permission हो।",
        "Maker-checker सर्व्हर-साइडवर enforce केला जातो: ज्याने PO raise केली आहे, तो स्वतः ती approve किंवा reject करू शकत नाही, जरी त्याच्याकडे approval permission असेल तरीही.",
        "Maker-checker server-side par enforce hota hai: jisne bhi PO raise ki hai, wo khud use approve ya reject nahi kar sakta, chahe uske paas approval permission ho.",
    ),
    "po-approvals.stepsHeading": (
        "Approval flow",
        "अनुमोदन प्रवाह",
        "मंजुरी प्रवाह",
        "Approval ka flow",
    ),
    "po-approvals.steps.0.label": ("Pending", "लंबित", "प्रलंबित", "Pending"),
    "po-approvals.steps.0.caption": (
        "PO raised and lands in this queue.",
        "PO raise होता है और इस queue में आता है।",
        "PO raise होते आणि या queue मध्ये येते.",
        "PO raise hota hai aur is queue mein aata hai.",
    ),
    "po-approvals.steps.1.label": ("Review", "समीक्षा", "पुनरावलोकन", "Review"),
    "po-approvals.steps.1.caption": (
        "Click Review to load line items and total.",
        "line items और total लोड करने के लिए Review पर क्लिक करें।",
        "line items आणि total लोड करण्यासाठी Review वर क्लिक करा.",
        "Line items aur total load karne ke liye Review par click karein.",
    ),
    "po-approvals.steps.2.label": ("Decision", "निर्णय", "निर्णय", "Decision"),
    "po-approvals.steps.2.caption": (
        "Approve or reject, with an optional remark.",
        "optional remark के साथ approve या reject करें।",
        "ऐच्छिक remark सह approve किंवा reject करा.",
        "Optional remark ke saath approve ya reject karein.",
    ),
    "po-approvals.steps.3.label": ("Off Queue", "क्यू से बाहर", "क्यूमधून बाहेर", "Queue se bahar"),
    "po-approvals.steps.3.caption": (
        "Decided PO leaves the list; approved POs proceed to GRN.",
        "निर्णय होने पर PO लिस्ट से हट जाता है; approved POs GRN की ओर बढ़ते हैं।",
        "निर्णय झाल्यावर PO यादीतून बाहेर जाते; approved POs GRN कडे पुढे जातात.",
        "Decision hone ke baad PO list se hat jaata hai; approved POs GRN ki taraf badhte hain.",
    ),
    "po-approvals.fieldRules.0.name": ("PO Number", "PO नंबर", "PO क्रमांक", "PO Number"),
    "po-approvals.fieldRules.0.description": (
        "Identifier assigned at creation; searchable in the queue.",
        "creation के समय दिया गया identifier; queue में searchable है।",
        "creation च्या वेळी दिलेला identifier; queue मध्ये searchable आहे.",
        "Creation ke time assign hua identifier; queue mein searchable hai.",
    ),
    "po-approvals.fieldRules.1.name": ("Vendor", "वेंडर", "व्हेंडर", "Vendor"),
    "po-approvals.fieldRules.1.description": (
        "Vendor the order was placed with; also searchable.",
        "वह vendor जिसके साथ order दिया गया था; यह भी searchable है।",
        "ज्या vendor सोबत order दिली गेली; हे देखील searchable आहे.",
        "Jis vendor ke saath order place hua tha; ye bhi searchable hai.",
    ),
    "po-approvals.fieldRules.2.name": ("Total Amount", "कुल राशि", "एकूण रक्कम", "Total Amount"),
    "po-approvals.fieldRules.2.description": (
        "Sum of all line items; shown in the queue and the review panel.",
        "सभी line items का योग; queue और review panel दोनों में दिखाई देता है।",
        "सर्व line items ची बेरीज; queue आणि review panel दोन्हीमध्ये दाखवली जाते.",
        "Sabhi line items ka sum; queue aur review panel dono mein dikhta hai.",
    ),
    "po-approvals.fieldRules.3.name": ("Remarks", "रिमार्क्स", "रिमार्क्स", "Remarks"),
    "po-approvals.fieldRules.3.description": (
        "Optional note recorded with the approve or reject decision.",
        "approve या reject decision के साथ दर्ज किया गया optional नोट।",
        "approve किंवा reject decision सोबत नोंदवलेली ऐच्छिक note.",
        "Approve ya reject decision ke saath record hui optional note.",
    ),
    "po-approvals.tip.title": (
        "Remarks don't clear when you switch POs",
        "PO बदलने पर Remarks क्लियर नहीं होते",
        "PO बदलल्यावर Remarks क्लिअर होत नाहीत",
        "PO switch karne par Remarks clear nahi hote",
    ),
    "po-approvals.tip.body": (
        "The Remarks box isn't cleared by clicking Review on a different PO — only by submitting a decision. If you type a note, then switch to reviewing another PO without deciding, that leftover text will be sent with whatever decision you make next.",
        "किसी दूसरे PO पर Review क्लिक करने से Remarks box क्लियर नहीं होता — यह केवल decision submit करने पर क्लियर होता है। यदि आप कोई नोट टाइप करते हैं और बिना निर्णय लिए किसी अन्य PO की समीक्षा करने लगते हैं, तो वह बचा हुआ text अगली बार जो भी decision लेंगे उसके साथ भेज दिया जाएगा।",
        "दुसऱ्या PO वर Review क्लिक केल्याने Remarks box क्लिअर होत नाही — तो फक्त decision submit केल्यावरच क्लिअर होतो. जर तुम्ही एखादी note टाइप करून, निर्णय न घेता दुसऱ्या PO चे पुनरावलोकन करू लागलात, तर तो शिल्लक राहिलेला text तुम्ही पुढे जो निर्णय घ्याल त्यासोबत पाठवला जाईल.",
        "Kisi doosre PO par Review click karne se Remarks box clear nahi hota — ye sirf decision submit karne par clear hota hai. Agar aap koi note type karke, bina decide kiye kisi aur PO ko review karne lagte hain, to wo bacha hua text aapke agle decision ke saath bhej diya jaayega.",
    ),
}


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_APPROVALS.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_APPROVALS)} po-approvals keys.")


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