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

Usage: docker compose exec api python seed_translations_pageinfo_purchase_order_detail.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_ORDER_DETAIL = {
    "purchase-order-detail.title": (
        "Purchase Order Details",
        "परचेज़ ऑर्डर विवरण",
        "परचेस ऑर्डर तपशील",
        "Purchase Order Details",
    ),
    "purchase-order-detail.subtitle": (
        "Purchase order · read-only",
        "परचेज़ ऑर्डर · केवल पढ़ने के लिए",
        "परचेस ऑर्डर · फक्त वाचण्यासाठी",
        "Purchase order · sirf read-only",
    ),
    "purchase-order-detail.body.0": (
        "Full detail view for a single purchase order — vendor, dates, the requisition/quotation it was raised from, and its decision trail.",
        "एक परचेज़ ऑर्डर का पूर्ण विवरण दृश्य — vendor, dates, वह requisition/quotation जिससे यह raise हुआ, और इसका decision trail।",
        "एका परचेस ऑर्डरचे संपूर्ण तपशीलवार दृश्य — vendor, dates, ज्या requisition/quotation मधून हे raise झाले, आणि त्याचा decision trail.",
        "Ek single purchase order ka full detail view — vendor, dates, wo requisition/quotation jisse ye raise hua, aur uska decision trail.",
    ),
    "purchase-order-detail.body.1": (
        "Also lists every asset acquired against this PO, mirroring the PO-wise Asset Report so you can check fulfillment without leaving the page.",
        "यह इस PO के विरुद्ध acquire किए गए हर asset को भी सूचीबद्ध करता है, PO-wise Asset Report की तरह, ताकि आप बिना page छोड़े fulfillment जाँच सकें।",
        "हे या PO विरुद्ध acquire केलेल्या प्रत्येक asset ची यादीही देते, PO-wise Asset Report प्रमाणे, जेणेकरून तुम्ही page न सोडता fulfillment तपासू शकाल.",
        "Ye is PO ke against acquire kiye gaye har asset ko bhi list karta hai, PO-wise Asset Report jaisa, taaki aap page chhode bina fulfillment check kar sako.",
    ),
    "purchase-order-detail.stepsHeading": (
        "PO lifecycle",
        "PO जीवनचक्र",
        "PO जीवनचक्र",
        "PO ka lifecycle",
    ),
    "purchase-order-detail.steps.0.label": ("Draft", "प्रारूप", "मसुदा", "Draft"),
    "purchase-order-detail.steps.0.caption": (
        "PO raised manually or from an awarded quotation; approval pending.",
        "PO manually raise किया गया या awarded quotation से; approval pending है।",
        "PO manually raise केले किंवा awarded quotation मधून; approval pending आहे.",
        "PO manually raise hua ya awarded quotation se; approval pending hai.",
    ),
    "purchase-order-detail.steps.1.label": ("Approved / Rejected", "स्वीकृत / अस्वीकृत", "मंजूर / नामंजूर", "Approved / Rejected"),
    "purchase-order-detail.steps.1.caption": (
        "Approver decides in PO Approvals; decision and notes are recorded here.",
        "Approver, PO Approvals में निर्णय लेता है; decision और notes यहाँ record होते हैं।",
        "Approver, PO Approvals मध्ये निर्णय घेतो; decision आणि notes येथे record होतात.",
        "Approver PO Approvals mein decide karta hai; decision aur notes yahan record hote hain.",
    ),
    "purchase-order-detail.steps.2.label": ("Open", "खुला", "खुले", "Open"),
    "purchase-order-detail.steps.2.caption": (
        "Active PO — goods receipt (GRN) and invoice verification proceed against it.",
        "Active PO — इसके विरुद्ध goods receipt (GRN) और invoice verification आगे बढ़ते हैं।",
        "Active PO — याविरुद्ध goods receipt (GRN) आणि invoice verification पुढे जातात.",
        "Active PO — iske against goods receipt (GRN) aur invoice verification proceed hota hai.",
    ),
    "purchase-order-detail.steps.3.label": ("Closed", "बंद", "बंद", "Closed"),
    "purchase-order-detail.steps.3.caption": (
        "Marked closed once receiving and invoicing are complete.",
        "Receiving और invoicing पूरी होने पर इसे closed mark कर दिया जाता है।",
        "Receiving आणि invoicing पूर्ण झाल्यावर हे closed mark केले जाते.",
        "Receiving aur invoicing complete hone ke baad ise closed mark kar diya jaata hai.",
    ),
    "purchase-order-detail.fieldRules.0.name": ("PO Status", "PO स्टेटस", "PO स्टेटस", "PO Status"),
    "purchase-order-detail.fieldRules.0.description": (
        "draft / open / closed — changes only via approve or close actions elsewhere, never edited here.",
        "draft / open / closed — बदलाव केवल कहीं और approve या close actions के ज़रिए होते हैं, यहाँ कभी edit नहीं होता।",
        "draft / open / closed — बदल फक्त इतरत्र approve किंवा close actions द्वारे होतात, इथे कधीही edit केले जात नाही.",
        "draft / open / closed — changes sirf kahin aur approve ya close actions se hote hain, yahan kabhi edit nahi hota.",
    ),
    "purchase-order-detail.fieldRules.1.name": ("Approval Status", "अप्रूवल स्टेटस", "अप्रूव्हल स्टेटस", "Approval Status"),
    "purchase-order-detail.fieldRules.1.description": (
        "pending / approved / rejected — set from the PO Approvals queue, not from this page.",
        "pending / approved / rejected — यह PO Approvals queue से set होता है, इस page से नहीं।",
        "pending / approved / rejected — हे PO Approvals queue मधून set होते, या page वरून नाही.",
        "pending / approved / rejected — ye PO Approvals queue se set hota hai, is page se nahi.",
    ),
    "purchase-order-detail.fieldRules.2.name": ("Requisition / Quotation", "रिक्विज़िशन / कोटेशन", "रिक्विझिशन / कोटेशन", "Requisition / Quotation"),
    "purchase-order-detail.fieldRules.2.description": (
        "Shows the originating PR or awarded quote; \"—\" means the PO was raised manually.",
        "मूल PR या awarded quote दिखाता है; \"—\" का मतलब है कि PO manually raise किया गया था।",
        "मूळ PR किंवा awarded quote दाखवते; \"—\" म्हणजे PO manually raise केले होते.",
        "Originating PR ya awarded quote dikhata hai; \"—\" ka matlab hai PO manually raise hua tha.",
    ),
    "purchase-order-detail.fieldRules.3.name": ("Assets Purchased", "खरीदी गई Assets", "खरेदी केलेल्या Assets", "Assets Purchased"),
    "purchase-order-detail.fieldRules.3.description": (
        "Auto-populated from assets acquired against this PO — not a manually entered list.",
        "इस PO के विरुद्ध acquire की गई assets से auto-populate होता है — यह manually entered list नहीं है।",
        "या PO विरुद्ध acquire केलेल्या assets मधून auto-populate होते — ही manually entered यादी नाही.",
        "Is PO ke against acquire hui assets se auto-populate hota hai — ye manually entered list nahi hai.",
    ),
    "purchase-order-detail.tip.title": (
        "This page is view-only",
        "यह page केवल देखने के लिए है",
        "हे page फक्त पाहण्यासाठी आहे",
        "Ye page sirf view-only hai",
    ),
    "purchase-order-detail.tip.body": (
        "There's no approve/reject/close action here — do that from PO Approvals or the Purchase Orders list, then come back to see the updated status and decision notes.",
        "यहाँ कोई approve/reject/close action नहीं है — वह PO Approvals या Purchase Orders list से करें, फिर updated status और decision notes देखने के लिए वापस आएँ।",
        "इथे कोणतीही approve/reject/close action नाही — ती PO Approvals किंवा Purchase Orders यादीतून करा, नंतर updated status आणि decision notes पाहण्यासाठी परत या.",
        "Yahan koi approve/reject/close action nahi hai — wo PO Approvals ya Purchase Orders list se karein, phir updated status aur decision notes dekhne ke liye wapas aayein.",
    ),
}


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_ORDER_DETAIL.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_ORDER_DETAIL)} purchase-order-detail keys.")


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