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

Usage: docker compose exec api python seed_translations_pageinfo_pr_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)
PR_APPROVALS = {
    "pr-approvals.title": (
        "PR Approval Queue",
        "PR अनुमोदन कतार",
        "PR मंजुरी रांग",
        "PR Approval Queue",
    ),
    "pr-approvals.subtitle": (
        "The maker-checker gate a submitted requisition must clear before it can move to RFQ.",
        "सबमिट की गई requisition को RFQ में आगे बढ़ने से पहले जिस maker-checker गेट को पार करना ज़रूरी है।",
        "सबमिट केलेल्या requisition ला RFQ मध्ये पुढे जाण्यापूर्वी ज्या maker-checker गेटमधून पार व्हावे लागते.",
        "Maker-checker gate jise submit ki gayi requisition ko RFQ mein aage badhne se pehle clear karna hota hai.",
    ),
    "pr-approvals.body.0": (
        "Purchase requisitions awaiting approval decision.",
        "Purchase requisitions जो अनुमोदन निर्णय की प्रतीक्षा में हैं।",
        "Purchase requisitions ज्या मंजुरी निर्णयाच्या प्रतीक्षेत आहेत.",
        "Purchase requisitions jo approval decision ka wait kar rahi hain.",
    ),
    "pr-approvals.body.1": (
        "Only requisitions in \"Pending Approval\" status show up here. Approving or rejecting is final for this queue — the PR leaves the list either way and the requestor is not the one who decides it.",
        "केवल \"Pending Approval\" स्थिति वाली requisitions ही यहाँ दिखती हैं। Approve या reject करना इस queue के लिए अंतिम होता है — दोनों ही स्थिति में PR लिस्ट से बाहर हो जाता है, और requestor खुद इसका निर्णय नहीं करता।",
        "केवळ \"Pending Approval\" स्थितीतील requisitions इथे दिसतात. Approve किंवा reject करणे या queue साठी अंतिम असते — दोन्ही परिस्थितीत PR यादीतून बाहेर जाते, आणि requestor स्वतः त्याचा निर्णय घेत नाही.",
        "Sirf \"Pending Approval\" status wali requisitions hi yahan dikhti hain. Approve ya reject karna is queue ke liye final hota hai — dono case mein PR list se nikal jaata hai, aur requestor khud iska decision nahi karta.",
    ),
    "pr-approvals.stepsHeading": (
        "How a decision is made",
        "निर्णय कैसे लिया जाता है",
        "निर्णय कसा घेतला जातो",
        "Decision kaise liya jaata hai",
    ),
    "pr-approvals.steps.0.label": ("Select PR", "PR चुनें", "PR निवडा", "PR Select karein"),
    "pr-approvals.steps.0.caption": (
        "Pick a pending requisition from the queue list to load it in the review panel.",
        "Review panel में लोड करने के लिए queue list से कोई pending requisition चुनें।",
        "Review panel मध्ये लोड करण्यासाठी queue list मधून एखादी pending requisition निवडा.",
        "Review panel mein load karne ke liye queue list se koi pending requisition pick karein.",
    ),
    "pr-approvals.steps.1.label": ("Review Items & Cost", "Items और Cost की समीक्षा करें", "Items आणि Cost चा आढावा घ्या", "Items & Cost Review karein"),
    "pr-approvals.steps.1.caption": (
        "Check the line items and estimated cost against the request.",
        "Request के मुक़ाबले line items और estimated cost जाँचें।",
        "Request च्या तुलनेत line items आणि estimated cost तपासा.",
        "Request ke against line items aur estimated cost check karein.",
    ),
    "pr-approvals.steps.2.label": ("Add Remarks", "Remarks जोड़ें", "Remarks जोडा", "Remarks Add karein"),
    "pr-approvals.steps.2.caption": (
        "Optional notes recorded alongside the decision.",
        "निर्णय के साथ दर्ज किए जाने वाले वैकल्पिक notes।",
        "निर्णयासोबत नोंदवले जाणारे ऐच्छिक notes.",
        "Decision ke saath record hone wale optional notes.",
    ),
    "pr-approvals.steps.3.label": ("Approve or Reject", "Approve या Reject करें", "Approve किंवा Reject करा", "Approve ya Reject karein"),
    "pr-approvals.steps.3.caption": (
        "Submits the decision; the PR leaves this queue immediately.",
        "निर्णय सबमिट करता है; PR तुरंत इस queue से बाहर हो जाता है।",
        "निर्णय सबमिट करते; PR लगेच या queue मधून बाहेर जाते.",
        "Decision submit karta hai; PR turant is queue se nikal jaata hai.",
    ),
    "pr-approvals.fieldRules.0.name": ("PR Number", "PR नंबर", "PR नंबर", "PR Number"),
    "pr-approvals.fieldRules.0.description": (
        "Unique identifier of the requisition; also the row you click to load it into the review panel.",
        "Requisition का unique पहचानकर्ता; साथ ही वह row भी जिस पर क्लिक करने से यह review panel में लोड होता है।",
        "Requisition चा unique ओळखकर्ता; तसेच ती row जिच्यावर क्लिक केल्याने ती review panel मध्ये लोड होते.",
        "Requisition ka unique identifier; aur wo row bhi jispar click karke ise review panel mein load kiya jaata hai.",
    ),
    "pr-approvals.fieldRules.1.name": ("Estimated Cost", "अनुमानित लागत", "अंदाजित खर्च", "Estimated Cost"),
    "pr-approvals.fieldRules.1.description": (
        "Total value of all line items on the requisition, shown for quick triage in the list and detail panel.",
        "Requisition के सभी line items का कुल मूल्य, जो list और detail panel में त्वरित triage के लिए दिखाया जाता है।",
        "Requisition वरील सर्व line items ची एकूण किंमत, जी list आणि detail panel मध्ये त्वरित triage साठी दाखवली जाते.",
        "Requisition ke saare line items ki total value, jo list aur detail panel mein quick triage ke liye dikhayi jaati hai.",
    ),
    "pr-approvals.fieldRules.2.name": ("Priority", "प्राथमिकता", "प्राधान्य", "Priority"),
    "pr-approvals.fieldRules.2.description": (
        "Critical/High/Normal/Low set by the requestor; informational only, does not gate the decision.",
        "Requestor द्वारा सेट किया गया Critical/High/Normal/Low; यह केवल जानकारी के लिए है, निर्णय को नहीं रोकता।",
        "Requestor ने सेट केलेले Critical/High/Normal/Low; हे फक्त माहितीसाठी आहे, निर्णयाला अडवत नाही.",
        "Requestor dwara set kiya gaya Critical/High/Normal/Low; ye sirf informational hai, decision ko gate nahi karta.",
    ),
    "pr-approvals.fieldRules.3.name": ("Remarks", "Remarks", "Remarks", "Remarks"),
    "pr-approvals.fieldRules.3.description": (
        "Optional free-text note sent with the approve/reject call; left blank if not filled in.",
        "Approve/reject call के साथ भेजा जाने वाला वैकल्पिक free-text note; न भरने पर खाली रहता है।",
        "Approve/reject call सोबत पाठवला जाणारा ऐच्छिक free-text note; न भरल्यास रिकामा राहतो.",
        "Approve/reject call ke saath bheja jaane wala optional free-text note; agar fill nahi kiya to blank reh jaata hai.",
    ),
    "pr-approvals.tip.title": (
        "You can't approve your own PR",
        "आप अपने PR को खुद approve नहीं कर सकते",
        "तुम्ही स्वतःची PR स्वतः approve करू शकत नाही",
        "Aap apni PR khud approve nahi kar sakte",
    ),
    "pr-approvals.tip.body": (
        "If you raised the selected requisition, Approve/Reject are disabled here (maker-checker) — the backend enforces the same rule server-side as a backstop, so it's not just a UI restriction you can work around by resubmitting.",
        "अगर आपने चुनी गई requisition raise की है, तो यहाँ Approve/Reject अक्षम रहते हैं (maker-checker) — backend भी backstop के रूप में server-side पर यही rule लागू करता है, इसलिए यह केवल एक UI restriction नहीं है जिसे resubmit करके bypass किया जा सके।",
        "जर तुम्ही निवडलेली requisition raise केली असेल, तर इथे Approve/Reject अक्षम राहतात (maker-checker) — backend सुद्धा backstop म्हणून server-side वर हाच rule लागू करतो, त्यामुळे हे फक्त एक UI restriction नाही जे resubmit करून टाळता येईल.",
        "Agar aapne selected requisition raise ki hai, to yahan Approve/Reject disabled rehte hain (maker-checker) — backend bhi backstop ke roop mein server-side par yehi rule enforce karta hai, isliye ye sirf ek UI restriction nahi hai jise resubmit karke bypass kiya ja sake.",
    ),
}


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 PR_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(PR_APPROVALS)} pr-approvals keys.")


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