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

Usage: docker compose exec api python seed_translations_pageinfo_inventory_requests.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)
INVENTORY_REQUESTS = {
    "inventory-requests.title": (
        "Inventory Requests",
        "इन्वेंटरी अनुरोध",
        "इन्व्हेंटरी विनंत्या",
        "Inventory Requests",
    ),
    "inventory-requests.subtitle": (
        "Requisition, approve, and issue stock, and what each status means",
        "स्टॉक को requisition, approve और issue करना, और प्रत्येक status का क्या मतलब है",
        "स्टॉक requisition, approve आणि issue करणे, आणि प्रत्येक status चा अर्थ काय आहे",
        "Stock ko requisition, approve, aur issue karna, aur har status ka kya matlab hai",
    ),
    "inventory-requests.body.0": (
        "Requisition, approve, and issue inventory items to requesters.",
        "Requesters को inventory items requisition, approve और issue करना।",
        "Requesters ना inventory items requisition, approve आणि issue करणे.",
        "Requesters ko inventory items requisition, approve, aur issue karna.",
    ),
    "inventory-requests.body.1": (
        "A requester picks an item and quantity here; an approver signs off or rejects it; once approved, the item is issued out of stock against the request.",
        "यहाँ एक requester कोई item और quantity चुनता है; एक approver उसे sign off करता है या reject करता है; approve होने के बाद, वह item request के विरुद्ध stock से issue कर दिया जाता है।",
        "येथे एक requester एखादी item आणि quantity निवडतो; एक approver ती sign off करतो किंवा reject करतो; approve झाल्यावर, ती item request च्या विरुद्ध stock मधून issue केली जाते.",
        "Yahan ek requester koi item aur quantity choose karta hai; ek approver use sign off ya reject karta hai; approve hone ke baad, wo item request ke against stock se issue kar diya jaata hai.",
    ),
    "inventory-requests.stepsHeading": (
        "Request lifecycle",
        "अनुरोध जीवनचक्र",
        "विनंती जीवनचक्र",
        "Request lifecycle",
    ),
    "inventory-requests.steps.0.label": ("Pending", "लंबित", "प्रलंबित", "Pending"),
    "inventory-requests.steps.0.caption": (
        "Submitted, awaiting approval",
        "सबमिट किया गया, approval की प्रतीक्षा में",
        "सबमिट केले, approval ची प्रतीक्षा",
        "Submit ho gaya hai, approval ka wait ho raha hai",
    ),
    "inventory-requests.steps.1.label": ("Approved", "स्वीकृत", "मंजूर", "Approved"),
    "inventory-requests.steps.1.caption": (
        "Signed off, ready to issue",
        "Sign off हो गया, issue करने के लिए तैयार",
        "Sign off झाले, issue करण्यासाठी तयार",
        "Sign off ho gaya hai, issue karne ke liye ready hai",
    ),
    "inventory-requests.steps.2.label": ("Issued", "जारी किया गया", "जारी केले", "Issued"),
    "inventory-requests.steps.2.caption": (
        "Stock handed out, on-hand qty reduced",
        "Stock सौंप दिया गया, on-hand quantity कम हो गई",
        "Stock दिला गेला, on-hand quantity कमी झाली",
        "Stock hand out ho gaya, on-hand qty kam ho gayi",
    ),
    "inventory-requests.steps.3.label": ("Rejected", "अस्वीकृत", "नाकारले", "Rejected"),
    "inventory-requests.steps.3.caption": (
        "Declined with a reason, request closed",
        "कारण सहित अस्वीकार किया गया, request बंद",
        "कारणासह नाकारले, request बंद",
        "Reason ke saath decline ho gaya, request close ho gayi",
    ),
    "inventory-requests.fieldRules.0.name": ("Item", "आइटम", "आयटम", "Item"),
    "inventory-requests.fieldRules.0.description": (
        "Active inventory item being requested or issued; the Submit/Issue button stays disabled until one is picked.",
        "वह active inventory item जिसे request या issue किया जा रहा है; जब तक कोई item नहीं चुना जाता, Submit/Issue बटन disabled रहता है।",
        "जी active inventory item request किंवा issue केली जात आहे; जोपर्यंत एखादी item निवडली जात नाही, तोपर्यंत Submit/Issue बटण disabled राहते.",
        "Wo active inventory item jise request ya issue kiya ja raha hai; jab tak koi item pick nahi hoti, Submit/Issue button disabled rehta hai.",
    ),
    "inventory-requests.fieldRules.1.name": ("Quantity", "मात्रा", "प्रमाण", "Quantity"),
    "inventory-requests.fieldRules.1.description": (
        "Numeric amount requested or issued; also required before Submit/Issue enables.",
        "Request या issue की जाने वाली संख्यात्मक मात्रा; Submit/Issue enable होने से पहले यह भी आवश्यक है।",
        "Request किंवा issue केली जाणारी संख्यात्मक मात्रा; Submit/Issue enable होण्यापूर्वी हे देखील आवश्यक आहे.",
        "Request ya issue ki jaane wali numeric quantity; Submit/Issue enable hone se pehle ye bhi zaroori hai.",
    ),
    "inventory-requests.fieldRules.2.name": ("Justification", "औचित्य", "औचित्य", "Justification"),
    "inventory-requests.fieldRules.2.description": (
        "Free-text reason shown in the table; helps the approver decide.",
        "Table में दिखाया गया free-text कारण; approver को निर्णय लेने में मदद करता है।",
        "Table मध्ये दाखवलेले free-text कारण; approver ला निर्णय घेण्यास मदत करते.",
        "Table mein dikhne wala free-text reason; approver ko decide karne mein madad karta hai.",
    ),
    "inventory-requests.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "inventory-requests.fieldRules.3.description": (
        "Pending, Approved, Issued, or Rejected; controls which action buttons appear on that row.",
        "Pending, Approved, Issued, या Rejected; यह तय करता है कि उस row पर कौन-से action buttons दिखेंगे।",
        "Pending, Approved, Issued, किंवा Rejected; हे ठरवते की त्या row वर कोणती action buttons दिसतील.",
        "Pending, Approved, Issued, ya Rejected; ye decide karta hai ki us row par kaunse action buttons dikhenge.",
    ),
    "inventory-requests.fieldRules.4.name": ("Location", "लोकेशन", "लोकेशन", "Location"),
    "inventory-requests.fieldRules.4.description": (
        "Warehouse/location stock is issued from; optional on the Issue form.",
        "वह warehouse/location जहाँ से stock issue किया जाता है; Issue फ़ॉर्म पर यह वैकल्पिक है।",
        "जिथून stock issue केला जातो ते warehouse/location; Issue फॉर्मवर हे ऐच्छिक आहे.",
        "Wo warehouse/location jahan se stock issue hota hai; Issue form par ye optional hai.",
    ),
    "inventory-requests.tip.title": (
        "Issue needs create, not approve, permission",
        "Issue के लिए create permission चाहिए, approve नहीं",
        "Issue साठी create permission आवश्यक आहे, approve नाही",
        "Issue ke liye create permission chahiye, approve nahi",
    ),
    "inventory-requests.tip.body": (
        "The Issue button only shows up for users with inventory:create — not inventory:approve. Someone who approves a request may not be able to issue it themselves; that needs a user with create permission.",
        "Issue बटन केवल उन users को दिखाई देता है जिनके पास inventory:create है — inventory:approve नहीं। जो व्यक्ति किसी request को approve करता है, ज़रूरी नहीं कि वह खुद उसे issue भी कर सके; इसके लिए create permission वाले user की ज़रूरत होती है।",
        "Issue बटण फक्त त्या users ना दिसते ज्यांच्याकडे inventory:create आहे — inventory:approve नाही. जो व्यक्ती एखादी request approve करते, त्याला ती स्वतः issue करता येईलच असे नाही; त्यासाठी create permission असलेल्या user ची गरज असते.",
        "Issue button sirf un users ko dikhta hai jinke paas inventory:create hai — inventory:approve nahi. Jo request approve karta hai, zaroori nahi ki wo khud use issue bhi kar sake; uske liye create permission wale user ki zaroorat hoti hai.",
    ),
}


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 INVENTORY_REQUESTS.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(INVENTORY_REQUESTS)} inventory-requests keys.")


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