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

Usage: docker compose exec api python seed_translations_pageinfo_approval_queue.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)
APPROVAL_QUEUE = {
    "approval-queue.title": (
        "Master Approvals Queue",
        "मास्टर अप्रूवल्स क्यू",
        "मास्टर अप्रूव्हल्स क्यू",
        "Master Approvals Queue",
    ),
    "approval-queue.subtitle": (
        "The second sign-off every governed master record needs before it's usable",
        "उपयोग में आने से पहले हर governed master record को जिस दूसरे sign-off की ज़रूरत होती है",
        "वापरण्यायोग्य होण्यापूर्वी प्रत्येक governed master record ला आवश्यक असलेला दुसरा sign-off",
        "Usable hone se pehle har governed master record ko jo dusra sign-off chahiye hota hai",
    ),
    "approval-queue.body.0": (
        "Maker-checker queue across every governed master table (asset classes, locations, vendors, document types, cost centres) — the approver can never be the same user who created the record (GFR Rule 21).",
        "हर governed master table (asset classes, locations, vendors, document types, cost centres) में maker-checker queue — approver कभी भी वह user नहीं हो सकता जिसने record बनाया था (GFR Rule 21)।",
        "प्रत्येक governed master table (asset classes, locations, vendors, document types, cost centres) मधील maker-checker queue — approver तोच user कधीही असू शकत नाही ज्याने तो record तयार केला (GFR Rule 21).",
        "Har governed master table (asset classes, locations, vendors, document types, cost centres) mein maker-checker queue — approver kabhi bhi wahi user nahi ho sakta jisne record banaya tha (GFR Rule 21).",
    ),
    "approval-queue.body.1": (
        "There is no \"reject\" action; declining a change means leaving it unapproved and, if needed, asking the maker to edit or delete it.",
        "कोई \"reject\" action नहीं है; किसी बदलाव को अस्वीकार करने का मतलब है उसे unapproved छोड़ना और, ज़रूरत पड़ने पर, maker से उसे edit या delete करने के लिए कहना।",
        "कोणतीही \"reject\" action नाही; एखादा बदल नाकारणे म्हणजे तो unapproved सोडणे आणि, गरज असल्यास, maker ला तो edit किंवा delete करण्यास सांगणे.",
        "Koi \"reject\" action nahi hai; kisi change ko decline karne ka matlab hai use unapproved chhodna aur, zaroorat pade to, maker se use edit ya delete karne ko kehna.",
    ),
    "approval-queue.stepsHeading": (
        "How a record clears the queue",
        "एक record queue से कैसे क्लियर होता है",
        "एक record queue मधून कसा क्लियर होतो",
        "Ek record queue se kaise clear hota hai",
    ),
    "approval-queue.steps.0.label": ("Created", "बनाया गया", "तयार केले", "Created"),
    "approval-queue.steps.0.caption": (
        "A maker adds or edits a governed master record",
        "एक maker किसी governed master record को जोड़ता या edit करता है",
        "एक maker एखादा governed master record जोडतो किंवा edit करतो",
        "Ek maker koi governed master record add ya edit karta hai",
    ),
    "approval-queue.steps.1.label": ("Pending", "लंबित", "प्रलंबित", "Pending"),
    "approval-queue.steps.1.caption": (
        "Lands here, unusable elsewhere until cleared",
        "यहाँ आता है, क्लियर होने तक कहीं और उपयोग योग्य नहीं",
        "इथे येते, क्लियर होईपर्यंत इतरत्र वापरण्यायोग्य नसते",
        "Yahan aata hai, clear hone tak kahin aur usable nahi hota",
    ),
    "approval-queue.steps.2.label": ("Reviewed", "समीक्षित", "पुनरावलोकित", "Reviewed"),
    "approval-queue.steps.2.caption": (
        "A different user checks table, code, name, submitter",
        "एक अलग user table, code, name, submitter की जाँच करता है",
        "वेगळा user table, code, name, submitter तपासतो",
        "Ek different user table, code, name, submitter check karta hai",
    ),
    "approval-queue.steps.3.label": ("Approved", "स्वीकृत", "मंजूर", "Approved"),
    "approval-queue.steps.3.caption": (
        "Record becomes active and selectable tenant-wide",
        "Record active हो जाता है और पूरे tenant में चुना जा सकता है",
        "Record active होतो आणि संपूर्ण tenant मध्ये निवडण्यायोग्य होतो",
        "Record active ho jaata hai aur poore tenant mein select ho sakta hai",
    ),
    "approval-queue.fieldRules.0.name": ("Table", "टेबल", "टेबल", "Table"),
    "approval-queue.fieldRules.0.description": (
        "Which governed master type the record belongs to — asset class, location, vendor, document type or cost centre.",
        "Record किस governed master type से संबंधित है — asset class, location, vendor, document type या cost centre।",
        "हा record कोणत्या governed master type शी संबंधित आहे — asset class, location, vendor, document type किंवा cost centre.",
        "Record kis governed master type se belong karta hai — asset class, location, vendor, document type ya cost centre.",
    ),
    "approval-queue.fieldRules.1.name": ("Code", "कोड", "कोड", "Code"),
    "approval-queue.fieldRules.1.description": (
        "The record's unique code, shown as submitted — verify it before approving.",
        "Record का unique code, जैसा submit किया गया वैसा दिखाया गया — approve करने से पहले इसे verify करें।",
        "Record चा unique code, submit केल्याप्रमाणे दाखवला जातो — approve करण्यापूर्वी तो verify करा.",
        "Record ka unique code, jaise submit kiya gaya waise dikhaya gaya — approve karne se pehle isse verify karein.",
    ),
    "approval-queue.fieldRules.2.name": ("Submitted By", "किसके द्वारा सबमिट किया गया", "कोणी सबमिट केले", "Submitted By"),
    "approval-queue.fieldRules.2.description": (
        "The maker. The backend rejects an approval attempt by this same user.",
        "Maker। Backend इसी user द्वारा किए गए approval attempt को reject कर देता है।",
        "Maker. Backend त्याच user कडून केलेला approval attempt reject करतो.",
        "Maker hota hai. Backend isi user ke approval attempt ko reject kar deta hai.",
    ),
    "approval-queue.fieldRules.3.name": ("Submitted", "सबमिट किया गया", "सबमिट केले", "Submitted"),
    "approval-queue.fieldRules.3.description": (
        "When the record was created — older pending items deserve priority.",
        "Record कब बनाया गया था — पुराने pending items को प्राथमिकता मिलनी चाहिए।",
        "Record कधी तयार केला गेला — जुन्या pending items ला प्राधान्य मिळायला हवे.",
        "Record kab banaya gaya tha — purane pending items ko priority milni chahiye.",
    ),
    "approval-queue.tip.title": (
        "\"Approve All\" ignores the table filter",
        "\"Approve All\" table filter को अनदेखा करता है",
        "\"Approve All\" table filter दुर्लक्षित करते",
        "\"Approve All\" table filter ko ignore karta hai",
    ),
    "approval-queue.tip.body": (
        "Clicking the \"Tables Affected\" card filters the visible table, but the toolbar's \"Approve All\" button always approves every pending record across all tables, not just the filtered ones on screen. Use \"Approve Selected\" with checkboxes if you only want the filtered set.",
        "\"Tables Affected\" card पर क्लिक करने से visible table filter होती है, लेकिन toolbar का \"Approve All\" बटन हमेशा सभी tables के हर pending record को approve करता है, न कि केवल screen पर filtered records को। यदि आप केवल filtered set चाहते हैं तो checkboxes के साथ \"Approve Selected\" का उपयोग करें।",
        "\"Tables Affected\" card वर क्लिक केल्याने दृश्यमान table filter होते, पण toolbar चे \"Approve All\" बटण नेहमी सर्व tables मधील प्रत्येक pending record approve करते, फक्त screen वरील filtered records नाही. जर तुम्हाला फक्त filtered set हवा असेल तर checkboxes सह \"Approve Selected\" वापरा.",
        "\"Tables Affected\" card par click karne se visible table filter hoti hai, lekin toolbar ka \"Approve All\" button hamesha sabhi tables ke har pending record ko approve karta hai, sirf screen par filtered records ko nahi. Agar sirf filtered set chahiye to checkboxes ke saath \"Approve Selected\" use karein.",
    ),
}


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 APPROVAL_QUEUE.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(APPROVAL_QUEUE)} approval-queue keys.")


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