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

Usage: docker compose exec api python seed_translations_pageinfo_master_dashboard.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)
MASTER_DASHBOARD = {
    "master-dashboard.title": (
        "Master Data Dashboard",
        "मास्टर डेटा डैशबोर्ड",
        "मास्टर डेटा डॅशबोर्ड",
        "Master Data Dashboard",
    ),
    "master-dashboard.subtitle": (
        "How the tiles connect to each master register",
        "टाइलें प्रत्येक मास्टर रजिस्टर से कैसे जुड़ी हैं",
        "टाइल्स प्रत्येक मास्टर रजिस्टरशी कशा जोडलेल्या आहेत",
        "Tiles har master register se kaise connect hoti hain",
    ),
    "master-dashboard.body.0": (
        "Each tile shows a live record count for one master data category, fetched directly from that category's API — not a cached or fabricated number.",
        "प्रत्येक tile एक master data category के लिए live record count दिखाती है, जो सीधे उस category के API से fetch किया जाता है — यह कोई cached या fabricated संख्या नहीं है।",
        "प्रत्येक tile एका master data category साठी live record count दाखवते, जी थेट त्या category च्या API वरून fetch केली जाते — ही कोणतीही cached किंवा fabricated संख्या नाही.",
        "Har tile ek master data category ke liye live record count dikhati hai, jo directly us category ke API se fetch hota hai — ye koi cached ya fabricated number nahi hai.",
    ),
    "master-dashboard.body.1": (
        "Click a tile to drill into its actual records in a searchable, exportable table without leaving this page.",
        "इस page को छोड़े बिना किसी tile को क्लिक करें ताकि आप उसके actual records को एक searchable, exportable table में देख सकें।",
        "हे page न सोडता एखाद्या tile वर क्लिक करा म्हणजे तुम्ही तिच्या actual records ना एका searchable, exportable table मध्ये पाहू शकाल.",
        "Is page ko chhode bina kisi tile ko click karein taaki uske actual records ek searchable, exportable table mein khul jaayein.",
    ),
    "master-dashboard.stepsHeading": (
        "How you browse the data",
        "आप data कैसे browse करते हैं",
        "तुम्ही data कसे browse करता",
        "Aap data kaise browse karte hain",
    ),
    "master-dashboard.steps.0.label": ("Select Category", "श्रेणी चुनें", "श्रेणी निवडा", "Category select karein"),
    "master-dashboard.steps.0.caption": (
        "Click a tile — Asset Classes, Locations, Vendors, Document Types, or Cost Centres",
        "एक tile क्लिक करें — Asset Classes, Locations, Vendors, Document Types, या Cost Centres",
        "एक tile क्लिक करा — Asset Classes, Locations, Vendors, Document Types, किंवा Cost Centres",
        "Ek tile click karein — Asset Classes, Locations, Vendors, Document Types, ya Cost Centres",
    ),
    "master-dashboard.steps.1.label": ("Live Count", "लाइव गणना", "लाइव्ह गणना", "Live Count"),
    "master-dashboard.steps.1.caption": (
        "Counts are fetched from each master's API as the dashboard loads",
        "dashboard load होते समय प्रत्येक master के API से counts fetch किए जाते हैं",
        "dashboard load होताना प्रत्येक master च्या API वरून counts fetch केले जातात",
        "Dashboard load hote waqt har master ke API se counts fetch hote hain",
    ),
    "master-dashboard.steps.2.label": ("Drill Down", "गहराई में जाएं", "सखोल जा", "Drill Down karein"),
    "master-dashboard.steps.2.caption": (
        "An inline table of that category's real records opens below",
        "उस category के real records की एक inline table नीचे खुलती है",
        "त्या category च्या real records ची एक inline table खाली उघडते",
        "Us category ke real records ki ek inline table neeche khulti hai",
    ),
    "master-dashboard.steps.3.label": ("Resolve Gaps", "कमियां दूर करें", "त्रुटी दूर करा", "Gaps resolve karein"),
    "master-dashboard.steps.3.caption": (
        "Use Approval Queue or Validation Errors for anything pending or invalid",
        "pending या invalid किसी भी चीज़ के लिए Approval Queue या Validation Errors का उपयोग करें",
        "pending किंवा invalid असलेल्या कोणत्याही गोष्टीसाठी Approval Queue किंवा Validation Errors वापरा",
        "Pending ya invalid kisi bhi cheez ke liye Approval Queue ya Validation Errors use karein",
    ),
    "master-dashboard.fieldRules.0.name": ("Code", "कोड", "कोड", "Code"),
    "master-dashboard.fieldRules.0.description": (
        "Unique identifier; shows the vendor's GSTIN when a vendor row has no code.",
        "अद्वितीय identifier; जब किसी vendor row का कोई code नहीं होता, तो यह vendor का GSTIN दिखाता है।",
        "अद्वितीय identifier; जेव्हा एखाद्या vendor row ला code नसतो, तेव्हा हे vendor चा GSTIN दाखवते.",
        "Unique identifier; jab kisi vendor row ka koi code nahi hota, tab ye vendor ka GSTIN dikhata hai.",
    ),
    "master-dashboard.fieldRules.1.name": ("Name", "नाम", "नाव", "Name"),
    "master-dashboard.fieldRules.1.description": (
        "The record's display name — common across all five categories.",
        "record का display name — यह सभी पाँच categories में common है।",
        "record चे display name — हे सर्व पाच categories मध्ये common आहे.",
        "Record ka display name — ye sabhi paanch categories mein common hai.",
    ),
    "master-dashboard.fieldRules.2.name": ("Type / Description", "प्रकार / विवरण", "प्रकार / वर्णन", "Type / Description"),
    "master-dashboard.fieldRules.2.description": (
        "Shows the record's description, or vendor type for Vendors rows.",
        "record का description दिखाता है, या Vendors rows के लिए vendor type दिखाता है।",
        "record चे description दाखवते, किंवा Vendors rows साठी vendor type दाखवते.",
        "Record ka description dikhata hai, ya Vendors rows ke liye vendor type dikhata hai.",
    ),
    "master-dashboard.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "master-dashboard.fieldRules.3.description": (
        "Inactive only when is_active is explicitly false or status is 'inactive' — anything else displays as Active.",
        "केवल तभी Inactive होगा जब is_active स्पष्ट रूप से false हो या status 'inactive' हो — बाकी सभी मामलों में यह Active दिखता है।",
        "फक्त तेव्हाच Inactive असते जेव्हा is_active स्पष्टपणे false असते किंवा status 'inactive' असते — इतर सर्व प्रकरणांमध्ये ते Active दिसते.",
        "Sirf tabhi Inactive hoga jab is_active explicitly false ho ya status 'inactive' ho — baaki har case mein ye Active dikhta hai.",
    ),
    "master-dashboard.tip.title": (
        "Vendors load lazily",
        "Vendors lazily load होते हैं",
        "Vendors lazily load होतात",
        "Vendors lazily load hote hain",
    ),
    "master-dashboard.tip.body": (
        "Every other category's rows are fetched when the dashboard loads, but Vendors are paged in only when you open that tile (200 rows per request) — expect a short delay on the first click.",
        "बाकी सभी categories की rows dashboard load होते समय fetch हो जाती हैं, लेकिन Vendors केवल tile खोलने पर ही page-in होते हैं (प्रति request 200 rows) — पहली click पर थोड़ी देरी की उम्मीद रखें।",
        "इतर सर्व categories च्या rows dashboard load होताना fetch होतात, पण Vendors फक्त ती tile उघडल्यावरच page-in होतात (प्रति request 200 rows) — पहिल्या click वर थोडा विलंब अपेक्षित धरा.",
        "Baaki sabhi categories ki rows dashboard load hote waqt fetch ho jaati hain, lekin Vendors sirf tile open karne par hi page-in hoti hain (200 rows per request) — pehli click par thoda delay expect 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 MASTER_DASHBOARD.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(MASTER_DASHBOARD)} master-dashboard keys.")


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