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

Usage: docker compose exec api python seed_translations_pageinfo_procurement_history.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)
PROCUREMENT_HISTORY = {
    "procurement-history.title": (
        "Procurement History",
        "प्रोक्योरमेंट हिस्ट्री",
        "प्रोक्योरमेंट हिस्ट्री",
        "Procurement History",
    ),
    "procurement-history.subtitle": (
        "A unified, read-only log of procurement activity",
        "प्रोक्योरमेंट गतिविधि का एक एकीकृत, केवल-पठन (read-only) लॉग",
        "प्रोक्योरमेंट गतिविधीचा एकत्रित, फक्त-वाचनीय (read-only) लॉग",
        "Procurement activity ka ek unified, read-only log",
    ),
    "procurement-history.body.0": (
        "This page merges Purchase Requisitions and Purchase Orders into a single chronological feed — a combined view, not a separate record type of its own.",
        "यह पेज Purchase Requisitions और Purchase Orders को एक ही कालानुक्रमिक (chronological) feed में मिला देता है — यह एक संयुक्त view है, अपने आप में कोई अलग record type नहीं।",
        "हे पेज Purchase Requisitions आणि Purchase Orders यांना एकाच कालानुक्रमिक (chronological) feed मध्ये एकत्र करते — हे एक संयुक्त view आहे, स्वतःचा वेगळा record type नाही.",
        "Ye page Purchase Requisitions aur Purchase Orders ko ek hi chronological feed mein merge karta hai — ye ek combined view hai, apna alag record type nahi hai.",
    ),
    "procurement-history.body.1": (
        "Each row links to whatever documentation (invoice or goods-receipt DC) has been attached further along the procurement flow, so you can trace a reference number back to its paperwork without opening the source module.",
        "हर row उस documentation (invoice या goods-receipt DC) से लिंक होती है जो procurement flow में आगे attach की गई है, ताकि आप बिना source module खोले किसी reference number को उसके paperwork तक trace कर सकें।",
        "प्रत्येक row त्या documentation (invoice किंवा goods-receipt DC) शी लिंक होते जी procurement flow मध्ये पुढे attach केली गेली आहे, जेणेकरून तुम्ही source module न उघडता एखाद्या reference number चा paperwork पर्यंत trace करू शकाल.",
        "Har row us documentation (invoice ya goods-receipt DC) se link hoti hai jo procurement flow mein aage attach hui hai, taaki aap source module khole bina kisi reference number ko uske paperwork tak trace kar sakein.",
    ),
    "procurement-history.stepsHeading": (
        "How an entry gets here",
        "कोई entry यहाँ कैसे पहुँचती है",
        "एखादी entry इथे कशी पोहोचते",
        "Koi entry yahan kaise pahunchti hai",
    ),
    "procurement-history.steps.0.label": (
        "Requisition Raised",
        "Requisition रेज़ की गई",
        "Requisition रेझ केली",
        "Requisition Raised",
    ),
    "procurement-history.steps.0.caption": (
        'Approved PR logs as a "Requisition" row.',
        'Approved PR, "Requisition" row के रूप में लॉग होता है।',
        'Approved PR, "Requisition" row म्हणून लॉग होते.',
        'Approved PR "Requisition" row ke roop mein log hota hai.',
    ),
    "procurement-history.steps.1.label": (
        "PO Issued",
        "PO जारी किया गया",
        "PO जारी केला",
        "PO Issued",
    ),
    "procurement-history.steps.1.caption": (
        'PO raised from the PR logs as a "Purchase Order" row.',
        'PR से बनाया गया PO, "Purchase Order" row के रूप में लॉग होता है।',
        'PR मधून तयार केलेला PO, "Purchase Order" row म्हणून लॉग होतो.',
        'PR se raise hua PO "Purchase Order" row ke roop mein log hota hai.',
    ),
    "procurement-history.steps.2.label": (
        "Docs Attached",
        "Docs Attach किए गए",
        "Docs Attach केले",
        "Docs Attached",
    ),
    "procurement-history.steps.2.caption": (
        "GRN or invoice verification attaches supporting documents.",
        "GRN या invoice verification सहायक documents attach करता है।",
        "GRN किंवा invoice verification सहाय्यक documents attach करते.",
        "GRN ya invoice verification supporting documents attach karta hai.",
    ),
    "procurement-history.steps.3.label": (
        "Shown Here",
        "यहाँ दिखाया गया",
        "इथे दाखवले जाते",
        "Yahan Dikhta Hai",
    ),
    "procurement-history.steps.3.caption": (
        "Row appears with its current status and linked docs.",
        "Row अपनी current status और linked docs के साथ दिखाई देती है।",
        "Row तिच्या current status आणि linked docs सह दिसते.",
        "Row apni current status aur linked docs ke saath dikhti hai.",
    ),
    "procurement-history.fieldRules.0.name": (
        "Transaction Type",
        "ट्रांज़ैक्शन टाइप",
        "ट्रान्झॅक्शन टाइप",
        "Transaction Type",
    ),
    "procurement-history.fieldRules.0.description": (
        "Filters rows to Requisitions only, Purchase Orders only, or both.",
        "Rows को केवल Requisitions, केवल Purchase Orders, या दोनों तक filter करता है।",
        "Rows ला फक्त Requisitions, फक्त Purchase Orders, किंवा दोन्हींपर्यंत filter करते.",
        "Rows ko sirf Requisitions, sirf Purchase Orders, ya dono tak filter karta hai.",
    ),
    "procurement-history.fieldRules.1.name": (
        "Year",
        "वर्ष",
        "वर्ष",
        "Year",
    ),
    "procurement-history.fieldRules.1.description": (
        "Narrows rows to those dated within the selected calendar year.",
        "Rows को केवल चयनित calendar year की तारीखों तक सीमित करता है।",
        "Rows ला फक्त निवडलेल्या calendar year च्या तारखांपर्यंत मर्यादित करते.",
        "Rows ko sirf selected calendar year ki dates tak narrow karta hai.",
    ),
    "procurement-history.fieldRules.2.name": (
        "Search Reference Number",
        "Reference Number खोजें",
        "Reference Number शोधा",
        "Search Reference Number",
    ),
    "procurement-history.fieldRules.2.description": (
        "Case-insensitive substring match against the reference number.",
        "Reference number के विरुद्ध case-insensitive substring match।",
        "Reference number च्या विरुद्ध case-insensitive substring match.",
        "Reference number ke against case-insensitive substring match hota hai.",
    ),
    "procurement-history.fieldRules.3.name": (
        "Status",
        "स्थिति",
        "स्थिती",
        "Status",
    ),
    "procurement-history.fieldRules.3.description": (
        "Current lifecycle state of the underlying requisition or PO.",
        "अंतर्निहित (underlying) requisition या PO की वर्तमान lifecycle state।",
        "अंतर्निहित requisition किंवा PO ची सध्याची lifecycle state.",
        "Underlying requisition ya PO ki current lifecycle state.",
    ),
    "procurement-history.fieldRules.4.name": (
        "Documentation",
        "Documentation",
        "Documentation",
        "Documentation",
    ),
    "procurement-history.fieldRules.4.description": (
        "View/Download links for any attached invoice or goods-receipt DC.",
        "किसी भी attached invoice या goods-receipt DC के लिए View/Download links।",
        "कोणत्याही attached invoice किंवा goods-receipt DC साठी View/Download links.",
        "Kisi bhi attached invoice ya goods-receipt DC ke liye View/Download links.",
    ),
    "procurement-history.tip.title": (
        "Only the latest 100 records load",
        "केवल नवीनतम 100 records लोड होते हैं",
        "फक्त नवीनतम 100 records लोड होतात",
        "Sirf latest 100 records load hote hain",
    ),
    "procurement-history.tip.body": (
        "This page fetches just the most recent 100 combined transactions — there's no further pagination. If an older reference number isn't showing up, it may simply be outside that window; check the source Purchase Requisitions or Purchase Orders screen instead.",
        "यह पेज केवल सबसे हाल के 100 combined transactions fetch करता है — इससे आगे कोई pagination नहीं है। अगर कोई पुराना reference number नहीं दिख रहा, तो हो सकता है वह बस इस window से बाहर हो; इसके बजाय source Purchase Requisitions या Purchase Orders screen देखें।",
        "हे पेज फक्त अलीकडील 100 combined transactions fetch करते — याहून पुढे कोणतेही pagination नाही. जर एखादा जुना reference number दिसत नसेल, तर तो कदाचित या window च्या बाहेर असू शकतो; त्याऐवजी source Purchase Requisitions किंवा Purchase Orders screen तपासा.",
        "Ye page sirf sabse recent 100 combined transactions fetch karta hai — isse aage koi pagination nahi hai. Agar koi purana reference number nahi dikh raha, to ho sakta hai wo bas is window se bahar ho; iske bajaye source Purchase Requisitions ya Purchase Orders screen check 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 PROCUREMENT_HISTORY.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(PROCUREMENT_HISTORY)} procurement-history keys.")


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