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

Usage: docker compose exec api python seed_translations_pageinfo_rfq_detail.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)
RFQ_DETAIL = {
    "rfq-detail.title": (
        "RFQ Details",
        "RFQ विवरण",
        "RFQ तपशील",
        "RFQ Details",
    ),
    "rfq-detail.subtitle": (
        "Tendered items, invited vendors, and status for one request for quotation",
        "एक request for quotation के लिए tendered items, invited vendors, और status",
        "एका request for quotation साठी tendered items, invited vendors, आणि status",
        "Ek request for quotation ke tendered items, invited vendors, aur uska status",
    ),
    "rfq-detail.body.0": (
        "Read-only view of a single RFQ, opened from RFQ Management. It shows the items tendered (when raised from a requisition), which vendors were invited and when, and how many quotations have come back so far.",
        "एकल RFQ का read-only view, जो RFQ Management से open किया जाता है। यह वे items दिखाता है जो tender किए गए थे (जब किसी requisition से raise किया गया हो), कौन-से vendors को कब आमंत्रित किया गया, और अब तक कितनी quotations वापस आई हैं।",
        "एका RFQ चा read-only view, जो RFQ Management मधून open केला जातो. हे ते items दाखवते जे tender केले गेले (जेव्हा एखाद्या requisition मधून raise केले गेले असेल), कोणत्या vendors ना कधी आमंत्रित केले गेले, आणि आतापर्यंत किती quotations परत आल्या आहेत.",
        "Single RFQ ka read-only view, jo RFQ Management se open hota hai. Ye wo items dikhata hai jo tender kiye gaye the (jab requisition se raise hua ho), kaunse vendors ko invite kiya gaya tha aur kab, aur ab tak kitni quotations wapas aayi hain.",
    ),
    "rfq-detail.stepsHeading": (
        "RFQ lifecycle",
        "RFQ जीवनचक्र",
        "RFQ जीवनचक्र",
        "RFQ ka lifecycle",
    ),
    "rfq-detail.steps.0.label": ("Draft", "Draft", "Draft", "Draft"),
    "rfq-detail.steps.0.caption": (
        "Created with items, closing date, and invited vendors",
        "items, closing date, और invited vendors के साथ बनाया गया",
        "items, closing date, आणि invited vendors सह तयार केले",
        "Items, closing date, aur invited vendors ke saath create hota hai",
    ),
    "rfq-detail.steps.1.label": ("Open", "Open", "Open", "Open"),
    "rfq-detail.steps.1.caption": (
        "Vendors can submit quotations until the closing date",
        "Vendors closing date तक quotations सबमिट कर सकते हैं",
        "Vendors closing date पर्यंत quotations सबमिट करू शकतात",
        "Vendors closing date tak quotations submit kar sakte hain",
    ),
    "rfq-detail.steps.2.label": ("Closed", "Closed", "Closed", "Closed"),
    "rfq-detail.steps.2.caption": (
        "No more quotes accepted; ready for comparison",
        "अब और quotes स्वीकार नहीं किए जाते; comparison के लिए तैयार",
        "आता आणखी quotes स्वीकारले जात नाहीत; comparison साठी तयार",
        "Ab aur quotes accept nahi hote; comparison ke liye ready",
    ),
    "rfq-detail.steps.3.label": ("Awarded", "Awarded", "Awarded", "Awarded"),
    "rfq-detail.steps.3.caption": (
        "A winning quotation was selected",
        "एक विजेता quotation को चुना गया",
        "एक विजेता quotation निवडली गेली",
        "Ek winning quotation select ki gayi",
    ),
    "rfq-detail.steps.4.label": ("Cancelled", "Cancelled", "Cancelled", "Cancelled"),
    "rfq-detail.steps.4.caption": (
        "Withdrawn before award; can happen from any open state",
        "Award से पहले वापस लिया गया; किसी भी open state से हो सकता है",
        "Award होण्यापूर्वी मागे घेतले; कोणत्याही open state मधून होऊ शकते",
        "Award se pehle withdraw kiya gaya; kisi bhi open state se ho sakta hai",
    ),
    "rfq-detail.fieldRules.0.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "rfq-detail.fieldRules.0.description": (
        "Draft, Open, Closed, Awarded, or Cancelled — drives which actions are available on the RFQ list.",
        "Draft, Open, Closed, Awarded, या Cancelled — यह तय करता है कि RFQ list पर कौन-सी actions उपलब्ध हैं।",
        "Draft, Open, Closed, Awarded, किंवा Cancelled — हे ठरवते की RFQ list वर कोणत्या actions उपलब्ध आहेत.",
        "Draft, Open, Closed, Awarded, ya Cancelled — ye decide karta hai ki RFQ list par kaunsi actions available hain.",
    ),
    "rfq-detail.fieldRules.1.name": ("Closing Date", "क्लोज़िंग डेट", "क्लोझिंग डेट", "Closing Date"),
    "rfq-detail.fieldRules.1.description": (
        "Deadline for vendors to submit quotations; set at creation.",
        "Vendors द्वारा quotations सबमिट करने की अंतिम तिथि; निर्माण के समय सेट की जाती है।",
        "Vendors द्वारे quotations सबमिट करण्याची अंतिम तारीख; निर्मितीच्या वेळी सेट केली जाते.",
        "Vendors ke quotations submit karne ki deadline; creation ke time set hoti hai.",
    ),
    "rfq-detail.fieldRules.2.name": ("Requisition", "Requisition", "Requisition", "Requisition"),
    "rfq-detail.fieldRules.2.description": (
        "Source purchase requisition this RFQ was tendered from, if any — its items appear in the table below.",
        "वह source purchase requisition जिससे यह RFQ tender किया गया था, यदि कोई हो — इसके items नीचे table में दिखते हैं।",
        "ज्या source purchase requisition मधून हे RFQ tender केले गेले, असल्यास — त्याचे items खालील table मध्ये दिसतात.",
        "Wo source purchase requisition jisse ye RFQ tender hua tha, agar koi ho — uske items neeche table mein dikhte hain.",
    ),
    "rfq-detail.fieldRules.3.name": (
        "Vendors Invited / Responses",
        "वेंडर्स इनवाइटेड / रिस्पॉन्सेस",
        "वेंडर्स इनव्हाइटेड / रिस्पॉन्सेस",
        "Vendors Invited / Responses",
    ),
    "rfq-detail.fieldRules.3.description": (
        "Counts used to gauge response rate before closing the RFQ.",
        "RFQ बंद करने से पहले response rate का अंदाज़ा लगाने के लिए इस्तेमाल होने वाली counts।",
        "RFQ बंद करण्यापूर्वी response rate चा अंदाज घेण्यासाठी वापरल्या जाणाऱ्या counts.",
        "RFQ close karne se pehle response rate andaza lagane ke liye use hone wali counts.",
    ),
    "rfq-detail.tip.title": (
        "No actions here",
        "यहाँ कोई actions नहीं",
        "इथे कोणत्याही actions नाहीत",
        "Yahan koi actions nahi",
    ),
    "rfq-detail.tip.body": (
        "This page is read-only — closing, awarding, cancelling, and resending invites all happen from the RFQ Management list, not from this detail view.",
        "यह पेज read-only है — closing, awarding, cancelling, और invites resend करना — यह सब RFQ Management list से होता है, न कि इस detail view से।",
        "हे पेज read-only आहे — closing, awarding, cancelling, आणि invites resend करणे — हे सर्व RFQ Management list मधून होते, या detail view मधून नाही.",
        "Ye page read-only hai — closing, awarding, cancelling, aur invites resend karna sab RFQ Management list se hota hai, is detail view se nahi.",
    ),
}


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 RFQ_DETAIL.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(RFQ_DETAIL)} rfq-detail keys.")


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