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

Usage: docker compose exec api python seed_translations_pageinfo_purchase_requisitions.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)
PURCHASE_REQUISITIONS = {
    "purchase-requisitions.title": (
        "Purchase Requisitions",
        "पर्चेज़ रिक्विज़िशन्स",
        "पर्चेस रिक्विझिशन्स",
        "Purchase Requisitions",
    ),
    "purchase-requisitions.subtitle": (
        "Where a purchase starts, before there's any vendor or PO.",
        "वह जगह जहाँ खरीद की शुरुआत होती है, किसी vendor या PO से पहले।",
        "जिथे खरेदी सुरू होते, कोणत्याही vendor किंवा PO च्या आधी.",
        "Yahan se purchase shuru hota hai, kisi bhi vendor ya PO se pehle.",
    ),
    "purchase-requisitions.body.0": (
        "Register of internal purchase requests before they become purchase orders.",
        "आंतरिक खरीद अनुरोधों (purchase requests) का रजिस्टर, इससे पहले कि वे purchase orders बनें।",
        "अंतर्गत खरेदी विनंत्यांचे (purchase requests) रजिस्टर, त्या purchase orders बनण्यापूर्वी.",
        "Internal purchase requests ka register, purchase orders banne se pehle.",
    ),
    "purchase-requisitions.body.1": (
        "Add line items with quantity, unit price and GST, save as a draft, then submit it for approval. Approve/reject happens on the separate PR Approvals queue, not here.",
        "quantity, unit price और GST के साथ line items जोड़ें, draft के रूप में save करें, फिर approval के लिए submit करें। Approve/reject अलग PR Approvals queue पर होता है, यहाँ नहीं।",
        "quantity, unit price आणि GST सह line items जोडा, draft म्हणून save करा, नंतर approval साठी submit करा. Approve/reject वेगळ्या PR Approvals queue वर होते, इथे नाही.",
        "Quantity, unit price aur GST ke saath line items add karein, draft ke roop mein save karein, phir approval ke liye submit karein. Approve/reject alag PR Approvals queue par hota hai, yahan nahi.",
    ),
    "purchase-requisitions.stepsHeading": (
        "Requisition lifecycle",
        "रिक्विज़िशन लाइफ़साइकिल",
        "रिक्विझिशन लाइफसायकल",
        "Requisition ka lifecycle",
    ),
    "purchase-requisitions.steps.0.label": ("Draft", "ड्राफ्ट", "ड्राफ्ट", "Draft"),
    "purchase-requisitions.steps.0.caption": (
        "Save with department, priority and line items; still editable, can be deleted.",
        "department, priority और line items के साथ save करें; अभी भी editable है, delete किया जा सकता है।",
        "department, priority आणि line items सह save करा; अजूनही editable आहे, delete करता येते.",
        "Department, priority aur line items ke saath save hota hai; abhi bhi editable hai, delete kiya ja sakta hai.",
    ),
    "purchase-requisitions.steps.1.label": ("Submitted", "सबमिटेड", "सबमिटेड", "Submitted"),
    "purchase-requisitions.steps.1.caption": (
        "Sent for approval; no longer deletable, but a pending PR can still be edited.",
        "approval के लिए भेज दिया गया; अब delete नहीं किया जा सकता, लेकिन pending PR को अभी भी edit किया जा सकता है।",
        "approval साठी पाठवले गेले; आता delete करता येत नाही, पण pending PR अजूनही edit करता येते.",
        "Approval ke liye bhej diya gaya hai; ab delete nahi ho sakta, lekin pending PR ko abhi bhi edit kiya ja sakta hai.",
    ),
    "purchase-requisitions.steps.2.label": (
        "Approved / Rejected",
        "अप्रूव्ड / रिजेक्टेड",
        "अप्रूव्ह्ड / रिजेक्टेड",
        "Approved / Rejected",
    ),
    "purchase-requisitions.steps.2.caption": (
        "Decided on the PR Approvals queue by someone other than the requester.",
        "requester के अलावा किसी और द्वारा PR Approvals queue पर निर्णय लिया जाता है।",
        "requester व्यतिरिक्त इतर कोणीतरी PR Approvals queue वर निर्णय घेतो.",
        "Requester ke alawa koi aur PR Approvals queue par decision leta hai.",
    ),
    "purchase-requisitions.steps.3.label": ("RFQ", "RFQ", "RFQ", "RFQ"),
    "purchase-requisitions.steps.3.caption": (
        'Approved PRs get a "Create RFQ" action to move into vendor quoting.',
        'Approved PRs को vendor quoting में जाने के लिए "Create RFQ" action मिलता है।',
        'Approved PRs ना vendor quoting मध्ये जाण्यासाठी "Create RFQ" action मिळते.',
        'Approved PRs ko vendor quoting mein jaane ke liye "Create RFQ" action milta hai.',
    ),
    "purchase-requisitions.fieldRules.0.name": ("Department", "विभाग", "विभाग", "Department"),
    "purchase-requisitions.fieldRules.0.description": (
        "Org unit the request is raised for; drives who sees it in reports and dashboards.",
        "वह org unit जिसके लिए request उठाई गई है; यह तय करता है कि इसे reports और dashboards में कौन देखता है।",
        "ज्या org unit साठी request केली गेली आहे; हे ठरवते की reports आणि dashboards मध्ये ते कोण पाहतो.",
        "Jis org unit ke liye request raise hui hai; ye decide karta hai ki reports aur dashboards mein isse kaun dekhta hai.",
    ),
    "purchase-requisitions.fieldRules.1.name": ("Line items", "लाइन आइटम", "लाइन आयटम", "Line items"),
    "purchase-requisitions.fieldRules.1.description": (
        "At least one item with a name, quantity > 0 and unit price > 0 is required before you can save or submit.",
        "save या submit करने से पहले कम से कम एक item होना चाहिए जिसका name हो, quantity > 0 और unit price > 0 हो।",
        "save किंवा submit करण्यापूर्वी किमान एक item असणे आवश्यक आहे ज्याला name असेल, quantity > 0 आणि unit price > 0 असेल.",
        "Save ya submit karne se pehle kam se kam ek item chahiye jiska name ho, quantity > 0 aur unit price > 0 ho.",
    ),
    "purchase-requisitions.fieldRules.2.name": ("GST rate", "GST दर", "GST दर", "GST rate"),
    "purchase-requisitions.fieldRules.2.description": (
        'Optional per-line rate from the GST rates master; "Price includes GST" toggles whether the unit price is treated as inclusive or exclusive of that rate.',
        'GST rates master से वैकल्पिक per-line दर; "Price includes GST" यह तय करता है कि unit price को उस दर सहित (inclusive) माना जाए या रहित (exclusive)।',
        'GST rates master मधून ऐच्छिक per-line दर; "Price includes GST" हे ठरवते की unit price त्या दरासह (inclusive) मानली जाईल की त्याविना (exclusive).',
        'GST rates master se optional per-line rate; "Price includes GST" decide karta hai ki unit price us rate ke saath (inclusive) treat hogi ya uske bina (exclusive).',
    ),
    "purchase-requisitions.fieldRules.3.name": ("Priority", "प्राथमिकता", "प्राधान्य", "Priority"),
    "purchase-requisitions.fieldRules.3.description": (
        "Critical/High/Normal/Low — informational only, used for sorting and filtering the list.",
        "Critical/High/Normal/Low — केवल जानकारी के लिए, list को sort और filter करने में उपयोग होता है।",
        "Critical/High/Normal/Low — फक्त माहितीसाठी, list sort आणि filter करण्यासाठी वापरले जाते.",
        "Critical/High/Normal/Low — sirf informational hai, list ko sort aur filter karne ke liye use hota hai.",
    ),
    "purchase-requisitions.fieldRules.4.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "purchase-requisitions.fieldRules.4.description": (
        "Draft/Pending Approval/Approved/Rejected; controls which row actions (Edit, Submit, Delete, Create RFQ) are shown.",
        "Draft/Pending Approval/Approved/Rejected; यह तय करता है कि कौन-से row actions (Edit, Submit, Delete, Create RFQ) दिखाए जाएँ।",
        "Draft/Pending Approval/Approved/Rejected; हे ठरवते की कोणते row actions (Edit, Submit, Delete, Create RFQ) दाखवले जातील.",
        "Draft/Pending Approval/Approved/Rejected; ye decide karta hai ki kaunse row actions (Edit, Submit, Delete, Create RFQ) dikhenge.",
    ),
    "purchase-requisitions.tip.title": (
        "Estimated total is a preview only",
        "अनुमानित total केवल एक preview है",
        "अंदाजित total हा फक्त एक preview आहे",
        "Estimated total sirf ek preview hai",
    ),
    "purchase-requisitions.tip.body": (
        "The subtotal/GST/total shown while adding items is computed client-side from the GST rates loaded on page open — the backend recalculates authoritatively on save, so treat the form total as an estimate, not the final figure on the PR.",
        "items जोड़ते समय दिखाई देने वाला subtotal/GST/total, page खुलते समय load हुए GST rates से client-side पर calculate होता है — backend save करने पर authoritative रूप से इसे फिर से calculate करता है, इसलिए form total को एक अनुमान मानें, PR की अंतिम figure नहीं।",
        "items जोडताना दिसणारा subtotal/GST/total हा page उघडताना load झालेल्या GST rates वरून client-side वर calculate होतो — backend save केल्यावर authoritative पद्धतीने त्याची पुन्हा गणना करते, त्यामुळे form total ला एक अंदाज माना, PR वरील अंतिम figure नाही.",
        "Items add karte waqt dikhne wala subtotal/GST/total page open hote waqt load hue GST rates se client-side par calculate hota hai — backend save karne par isse authoritative tareeke se recalculate karta hai, isliye form total ko ek estimate maanein, PR ka final figure nahi.",
    ),
}


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 PURCHASE_REQUISITIONS.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(PURCHASE_REQUISITIONS)} purchase-requisitions keys.")


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