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

Usage: docker compose exec api python seed_translations_pageinfo_purchase_requisition_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_REQUISITION_DETAIL = {
    "purchase-requisition-detail.title": (
        "Purchase Requisition Details",
        "Purchase Requisition विवरण",
        "Purchase Requisition तपशील",
        "Purchase Requisition Details",
    ),
    "purchase-requisition-detail.subtitle": (
        "Requisition lifecycle & line items",
        "Requisition lifecycle और line items",
        "Requisition lifecycle आणि line items",
        "Requisition lifecycle aur line items",
    ),
    "purchase-requisition-detail.body.0": (
        "Full detail view for a single purchase requisition — requested items, approval status, and linked purchase order.",
        "एक purchase requisition का पूर्ण विवरण दृश्य — मांगे गए items, approval status, और लिंक किया गया purchase order.",
        "एका purchase requisition चे संपूर्ण तपशीलवार दृश्य — मागितलेल्या items, approval status, आणि लिंक केलेला purchase order.",
        "Ek single purchase requisition ka poora detail view — requested items, approval status, aur linked purchase order.",
    ),
    "purchase-requisition-detail.stepsHeading": (
        "Requisition lifecycle",
        "Requisition lifecycle",
        "Requisition lifecycle",
        "Requisition lifecycle",
    ),
    "purchase-requisition-detail.steps.0.label": ("Draft", "Draft", "Draft", "Draft"),
    "purchase-requisition-detail.steps.0.caption": (
        "Requestor adds items, quantities and estimated cost.",
        "Requestor items, quantities और estimated cost जोड़ता है।",
        "Requestor items, quantities आणि estimated cost जोडतो.",
        "Requestor items, quantities aur estimated cost add karta hai.",
    ),
    "purchase-requisition-detail.steps.1.label": ("Pending Approval", "Pending Approval", "Pending Approval", "Pending Approval"),
    "purchase-requisition-detail.steps.1.caption": (
        "Submitted and queued for a manager to decide.",
        "Submit किया गया और manager के निर्णय के लिए queue में रखा गया।",
        "Submit केले जाते आणि manager च्या निर्णयासाठी queue मध्ये ठेवले जाते.",
        "Submit ho jata hai aur manager ke decision ke liye queue mein rehta hai.",
    ),
    "purchase-requisition-detail.steps.2.label": ("Approved / Rejected", "Approved / Rejected", "Approved / Rejected", "Approved / Rejected"),
    "purchase-requisition-detail.steps.2.caption": (
        "Approver's decision, notes and timestamp are recorded here.",
        "Approver का निर्णय, notes और timestamp यहाँ दर्ज किए जाते हैं।",
        "Approver चा निर्णय, notes आणि timestamp येथे नोंदवले जातात.",
        "Approver ka decision, notes aur timestamp yahan record hote hain.",
    ),
    "purchase-requisition-detail.steps.3.label": ("RFQ Created", "RFQ Created", "RFQ Created", "RFQ Created"),
    "purchase-requisition-detail.steps.3.caption": (
        "Approved requisitions can be turned into an RFQ to gather vendor quotes.",
        "Approved requisitions को vendor quotes जुटाने के लिए RFQ में बदला जा सकता है।",
        "Approved requisitions ना vendor quotes मिळवण्यासाठी RFQ मध्ये रूपांतरित केले जाऊ शकते.",
        "Approved requisitions ko vendor quotes lene ke liye RFQ mein convert kiya ja sakta hai.",
    ),
    "purchase-requisition-detail.fieldRules.0.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "purchase-requisition-detail.fieldRules.0.description": (
        "draft, pending_approval, approved or rejected — set by the requisition and approval workflow, not editable here.",
        "draft, pending_approval, approved या rejected — requisition और approval workflow द्वारा सेट किया जाता है, यहाँ edit नहीं किया जा सकता।",
        "draft, pending_approval, approved किंवा rejected — requisition आणि approval workflow द्वारे सेट केले जाते, येथे edit करता येत नाही.",
        "draft, pending_approval, approved ya rejected — requisition aur approval workflow se set hota hai, yahan edit nahi ho sakta.",
    ),
    "purchase-requisition-detail.fieldRules.1.name": ("Priority", "प्राथमिकता", "प्राधान्य", "Priority"),
    "purchase-requisition-detail.fieldRules.1.description": (
        "critical, high, normal or low — helps approvers triage the approval queue.",
        "critical, high, normal या low — यह approvers को approval queue triage करने में मदद करता है।",
        "critical, high, normal किंवा low — हे approvers ना approval queue triage करण्यास मदत करते.",
        "critical, high, normal ya low — ye approvers ko approval queue triage karne mein help karta hai.",
    ),
    "purchase-requisition-detail.fieldRules.2.name": ("Estimated Cost", "अनुमानित लागत", "अंदाजित खर्च", "Estimated Cost"),
    "purchase-requisition-detail.fieldRules.2.description": (
        "Requestor's estimate at submission time; the Line Items total below is the actual computed sum.",
        "Requestor का submission के समय का अनुमान; नीचे Line Items का total ही असल computed sum है।",
        "Requestor चा submission वेळचा अंदाज; खालील Line Items चा total हाच खरा computed sum आहे.",
        "Requestor ka submission ke time ka estimate hai; niche Line Items ka total hi actual computed sum hai.",
    ),
    "purchase-requisition-detail.fieldRules.3.name": ("Line Items", "लाइन आइटम्स", "लाइन आयटम्स", "Line Items"),
    "purchase-requisition-detail.fieldRules.3.description": (
        "Item, quantity and unit price; each row's total and the grand total are computed client-side (qty × unit price).",
        "Item, quantity और unit price; हर row का total और grand total client-side पर computed होता है (qty × unit price)।",
        "Item, quantity आणि unit price; प्रत्येक row चा total आणि grand total client-side वर computed होतो (qty × unit price).",
        "Item, quantity aur unit price; har row ka total aur grand total client-side par computed hota hai (qty × unit price).",
    ),
    "purchase-requisition-detail.fieldRules.4.name": ("Decision Notes", "निर्णय नोट्स", "निर्णय नोट्स", "Decision Notes"),
    "purchase-requisition-detail.fieldRules.4.description": (
        "Approver's remarks, only shown once a decision has been made.",
        "Approver की टिप्पणियाँ, केवल निर्णय हो जाने के बाद ही दिखती हैं।",
        "Approver च्या टिप्पण्या, फक्त निर्णय झाल्यानंतरच दिसतात.",
        "Approver ki remarks, sirf decision ho jaane ke baad hi dikhti hain.",
    ),
    "purchase-requisition-detail.tip.title": (
        "Create RFQ only appears when approved",
        "Create RFQ केवल approved होने पर दिखता है",
        "Create RFQ फक्त approved झाल्यावर दिसतो",
        "Create RFQ sirf approved hone par dikhta hai",
    ),
    "purchase-requisition-detail.tip.body": (
        "The \"Create RFQ\" button only shows once status is approved — draft and pending requisitions must clear PR Approvals first.",
        "\"Create RFQ\" बटन तभी दिखता है जब status approved हो — draft और pending requisitions को पहले PR Approvals से गुज़रना होगा।",
        "\"Create RFQ\" बटण फक्त status approved झाल्यावरच दिसते — draft आणि pending requisitions ना आधी PR Approvals मधून जावे लागते.",
        "\"Create RFQ\" button tabhi dikhta hai jab status approved ho — draft aur pending requisitions ko pehle PR Approvals clear karne honge.",
    ),
}


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_REQUISITION_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_REQUISITION_DETAIL)} purchase-requisition-detail keys.")


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