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

Usage: docker compose exec api python seed_translations_pageinfo_quotation_comparison.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)
QUOTATION_COMPARISON = {
    "quotation-comparison.title": (
        "Quotation Comparison",
        "Quotation तुलना",
        "Quotation तुलना",
        "Quotation Comparison",
    ),
    "quotation-comparison.subtitle": (
        "Score vendor quotes and award the RFQ",
        "Vendor के quotes स्कोर करें और RFQ अवॉर्ड करें।",
        "Vendor च्या quotes ना score करा आणि RFQ अवॉर्ड करा.",
        "Vendor ke quotes ko score karo aur RFQ ko award karo.",
    ),
    "quotation-comparison.body.0": (
        "Pick an RFQ from the dropdown to see every quotation submitted against it, side by side, with the lowest bid, a spend chart and a technical-vs-commercial radar chart.",
        "Dropdown से कोई RFQ चुनें ताकि उसके विरुद्ध submit की गई हर quotation, lowest bid, एक spend chart और एक technical-vs-commercial radar chart के साथ, side-by-side देखी जा सके।",
        "Dropdown मधून एखादी RFQ निवडा जेणेकरून तिच्याविरुद्ध submit केलेली प्रत्येक quotation, lowest bid, एक spend chart आणि एक technical-vs-commercial radar chart यांसह, side-by-side पाहता येईल.",
        "Dropdown se koi RFQ select karo taaki uske against submit hui har quotation, lowest bid, ek spend chart aur ek technical-vs-commercial radar chart ke saath, side-by-side dikh jaaye.",
    ),
    "quotation-comparison.body.1": (
        "The Tech/Comm slider recomputes a Weighted Score live in your browser — it is not saved, so different reviewers can weigh price vs. quality differently without affecting each other.",
        "Tech/Comm slider आपके browser में live Weighted Score को फिर से calculate करता है — यह save नहीं होता, इसलिए अलग-अलग reviewers एक-दूसरे को प्रभावित किए बिना price बनाम quality को अलग-अलग तरीके से weigh कर सकते हैं।",
        "Tech/Comm slider तुमच्या browser मध्ये live Weighted Score पुन्हा calculate करतो — तो save होत नाही, त्यामुळे वेगवेगळे reviewers एकमेकांवर परिणाम न करता price विरुद्ध quality वेगवेगळ्या पद्धतीने weigh करू शकतात.",
        "Tech/Comm slider tumhare browser mein live Weighted Score ko recompute karta hai — ye save nahi hota, isliye alag-alag reviewers ek-doosre ko affect kiye bina price vs. quality ko alag tarah se weigh kar sakte hain.",
    ),
    "quotation-comparison.stepsHeading": (
        "Quotation lifecycle",
        "Quotation जीवनचक्र",
        "Quotation जीवनचक्र",
        "Quotation lifecycle",
    ),
    "quotation-comparison.steps.0.label": ("Submitted", "सबमिट किया गया", "सबमिट केलेले", "Submitted"),
    "quotation-comparison.steps.0.caption": (
        "Vendor's quote arrives (manually entered or via portal).",
        "Vendor का quote आता है (या तो manually enter किया जाता है या portal के ज़रिए)।",
        "Vendor चा quote येतो (एकतर manually enter केला जातो किंवा portal द्वारे).",
        "Vendor ka quote aata hai (ya to manually enter kiya jaata hai ya portal ke through).",
    ),
    "quotation-comparison.steps.1.label": ("Recommended", "रिकमंडेड", "रिकमंडेड", "Recommended"),
    "quotation-comparison.steps.1.caption": (
        "Reviewer flags a favourite using the Recommend button.",
        "Reviewer, Recommend button का उपयोग करके किसी पसंदीदा (favourite) quote को flag करता है।",
        "Reviewer, Recommend बटण वापरून एखादी favourite quote flag करतो.",
        "Reviewer, Recommend button use karke apni favourite quote ko flag karta hai.",
    ),
    "quotation-comparison.steps.2.label": ("Awarded", "अवॉर्डेड", "अवॉर्डेड", "Awarded"),
    "quotation-comparison.steps.2.caption": (
        "Once the RFQ is closed, Award marks this quote approved.",
        "एक बार RFQ closed हो जाए, तो Award इस quote को approved के रूप में mark कर देता है।",
        "एकदा RFQ closed झाली की, Award या quote ला approved म्हणून mark करतो.",
        "Ek baar RFQ close ho jaaye, to Award is quote ko approved mark kar deta hai.",
    ),
    "quotation-comparison.steps.3.label": ("PO Created", "PO क्रिएटेड", "PO क्रिएटेड", "PO Created"),
    "quotation-comparison.steps.3.caption": (
        "Approved quote converts straight into a purchase order.",
        "Approved quote सीधे एक purchase order में convert हो जाता है।",
        "Approved quote थेट एका purchase order मध्ये convert होतो.",
        "Approved quote seedhe ek purchase order mein convert ho jaata hai.",
    ),
    "quotation-comparison.fieldRules.0.name": ("Quoted Amount", "कोटेड अमाउंट", "कोटेड अमाउंट", "Quoted Amount"),
    "quotation-comparison.fieldRules.0.description": (
        "Vendor's total bid; drives the Lowest Bid card and the spend chart.",
        "Vendor की कुल bid; यह Lowest Bid card और spend chart को drive करती है।",
        "Vendor ची एकूण bid; ही Lowest Bid card आणि spend chart ला drive करते.",
        "Vendor ki total bid; ye Lowest Bid card aur spend chart ko drive karti hai.",
    ),
    "quotation-comparison.fieldRules.1.name": ("Weighted Score", "वेटेड स्कोर", "वेटेड स्कोर", "Weighted Score"),
    "quotation-comparison.fieldRules.1.description": (
        "tech_score × Tech% + comm_score × Comm%, recalculated as you move the slider.",
        "tech_score × Tech% + comm_score × Comm%, जो slider move करने पर फिर से calculate होता है।",
        "tech_score × Tech% + comm_score × Comm%, जो slider move केल्यावर पुन्हा calculate होते.",
        "tech_score × Tech% + comm_score × Comm%, jo slider move karne par phir se calculate hota hai.",
    ),
    "quotation-comparison.fieldRules.2.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "quotation-comparison.fieldRules.2.description": (
        "submitted / recommended / approved / rejected — gates which action button shows.",
        "submitted / recommended / approved / rejected — यह तय करता है कि कौन-सा action button दिखाई देगा।",
        "submitted / recommended / approved / rejected — हे ठरवते की कोणते action बटण दिसेल.",
        "submitted / recommended / approved / rejected — ye decide karta hai ki kaunsa action button dikhega.",
    ),
    "quotation-comparison.fieldRules.3.name": ("PDF", "PDF", "PDF", "PDF"),
    "quotation-comparison.fieldRules.3.description": (
        "Download link only appears once the antivirus scan finishes as \"clean\".",
        "Download link तभी दिखाई देता है जब antivirus scan \"clean\" के रूप में पूरा हो जाता है।",
        "Download link तेव्हाच दिसते जेव्हा antivirus scan \"clean\" म्हणून पूर्ण होते.",
        "Download link tabhi dikhta hai jab antivirus scan \"clean\" ke roop mein complete ho jaata hai.",
    ),
    "quotation-comparison.tip.title": (
        "Award only works on a closed RFQ",
        "Award केवल एक closed RFQ पर ही काम करता है",
        "Award फक्त एका closed RFQ वरच काम करते",
        "Award sirf ek closed RFQ par hi kaam karta hai",
    ),
    "quotation-comparison.tip.body": (
        "The Award button is hidden until the RFQ's own status is \"closed\" — if it's missing, go close the RFQ in RFQ Management first; Recommend works anytime.",
        "Award button तब तक hidden रहता है जब तक RFQ का अपना status \"closed\" न हो जाए — अगर यह missing है, तो पहले RFQ Management में जाकर RFQ को close करें; Recommend कभी भी काम करता है।",
        "Award बटण तोपर्यंत hidden राहते जोपर्यंत RFQ चा स्वतःचा status \"closed\" होत नाही — जर ते missing असेल, तर आधी RFQ Management मध्ये जाऊन RFQ close करा; Recommend कधीही काम करते.",
        "Award button tab tak hidden rehta hai jab tak RFQ ka apna status \"closed\" nahi ho jaata — agar ye missing hai, to pehle RFQ Management mein jaake RFQ close karo; Recommend kabhi bhi kaam karta 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 QUOTATION_COMPARISON.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(QUOTATION_COMPARISON)} quotation-comparison keys.")


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