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

Usage: docker compose exec api python seed_translations_pageinfo_inventory_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)
INVENTORY_DASHBOARD = {
    "inventory-dashboard.title": (
        "Inventory Dashboard",
        "इन्वेंटरी डैशबोर्ड",
        "इन्वेंटरी डॅशबोर्ड",
        "Inventory Dashboard",
    ),
    "inventory-dashboard.subtitle": (
        "A live control panel for stock, valuation, and open workflows",
        "स्टॉक, वैल्यूएशन और ओपन वर्कफ़्लो के लिए एक लाइव कंट्रोल पैनल",
        "स्टॉक, व्हॅल्युएशन आणि ओपन वर्कफ्लोसाठी एक लाइव्ह कंट्रोल पॅनेल",
        "Stock, valuation, aur open workflows ke liye ek live control panel",
    ),
    "inventory-dashboard.body.0": (
        "Live overview of stock items, low-stock alerts, valuation, and recent movements.",
        "स्टॉक items, low-stock अलर्ट, valuation, और हाल की movements का लाइव ओवरव्यू।",
        "स्टॉक items, low-stock अलर्ट्स, valuation, आणि अलीकडील movements चे लाइव्ह ओव्हरव्ह्यू.",
        "Stock items, low-stock alerts, valuation, aur recent movements ka live overview.",
    ),
    "inventory-dashboard.body.1": (
        "Every number on this page is computed from current inventory data — there is nothing to fill in here; it's a read-only summary that links into the underlying registers, reports and lists.",
        "इस पेज पर हर नंबर current inventory data से calculate किया जाता है — यहाँ कुछ भी भरने की ज़रूरत नहीं है; यह एक read-only सारांश है जो underlying registers, reports और lists से लिंक करता है।",
        "या पेजवरील प्रत्येक नंबर current inventory data वरून calculate केला जातो — इथे काहीही भरण्याची गरज नाही; हा एक read-only सारांश आहे जो underlying registers, reports आणि lists ला लिंक करतो.",
        "Is page par har number current inventory data se calculate hota hai — yahan kuch bhi fill karne ki zaroorat nahi hai; ye ek read-only summary hai jo underlying registers, reports aur lists se link karta hai.",
    ),
    "inventory-dashboard.stepsHeading": (
        "How to drill into a number",
        "किसी नंबर में ड्रिल कैसे करें",
        "एखाद्या नंबरमध्ये ड्रिल कसे करावे",
        "Kisi number mein drill kaise karein",
    ),
    "inventory-dashboard.steps.0.label": ("Scan cards", "कार्ड्स देखें", "कार्ड्स पहा", "Cards scan karein"),
    "inventory-dashboard.steps.0.caption": (
        "Six live counters: items, value, low stock, requests, audits, available stock",
        "छह लाइव काउंटर: items, value, low stock, requests, audits, available stock",
        "सहा लाइव्ह काउंटर्स: items, value, low stock, requests, audits, available stock",
        "Chhah live counters: items, value, low stock, requests, audits, available stock",
    ),
    "inventory-dashboard.steps.1.label": ("Click a card", "किसी कार्ड पर क्लिक करें", "एखाद्या कार्डवर क्लिक करा", "Kisi card par click karein"),
    "inventory-dashboard.steps.1.caption": (
        "Expands a detail table of the underlying rows below the grid",
        "यह grid के नीचे underlying rows की एक detail table खोलता है",
        "हे grid च्या खाली underlying rows ची एक detail table उघडते",
        "Grid ke niche underlying rows ki ek detail table expand hoti hai",
    ),
    "inventory-dashboard.steps.2.label": ("Sort / export", "सॉर्ट / एक्सपोर्ट करें", "सॉर्ट / एक्सपोर्ट करा", "Sort / export karein"),
    "inventory-dashboard.steps.2.caption": (
        "The detail table supports search, sort and CSV export like any register",
        "यह detail table किसी भी register की तरह search, sort और CSV export को सपोर्ट करती है",
        "ही detail table कोणत्याही register प्रमाणे search, sort आणि CSV export ला सपोर्ट करते",
        "Ye detail table kisi bhi register ki tarah search, sort aur CSV export support karti hai",
    ),
    "inventory-dashboard.steps.3.label": (
        "Click again to close",
        "बंद करने के लिए फिर से क्लिक करें",
        "बंद करण्यासाठी पुन्हा क्लिक करा",
        "Close karne ke liye dobara click karein",
    ),
    "inventory-dashboard.steps.3.caption": (
        "Same card toggles its own table shut",
        "वही कार्ड अपनी table को बंद कर देता है",
        "तेच कार्ड स्वतःची table बंद करते",
        "Wahi card apni table ko band kar deta hai",
    ),
    "inventory-dashboard.fieldRules.0.name": ("Total Items", "कुल आइटम्स", "एकूण आयटम्स", "Total Items"),
    "inventory-dashboard.fieldRules.0.description": (
        "Count of items in the master catalogue; drills into the full item list with code, category, unit and status.",
        "master catalogue में items की गिनती; यह code, category, unit और status के साथ पूरी item list में drill करता है।",
        "master catalogue मधील items ची संख्या; हे code, category, unit आणि status सह संपूर्ण item list मध्ये drill करते.",
        "Master catalogue mein items ki count; ye code, category, unit aur status ke saath poori item list mein drill karta hai.",
    ),
    "inventory-dashboard.fieldRules.1.name": ("Stock Value", "स्टॉक वैल्यू", "स्टॉक व्हॅल्यू", "Stock Value"),
    "inventory-dashboard.fieldRules.1.description": (
        "Total valuation across items per each item's costing method; drills into the Stock Valuation report.",
        "हर item की costing method के अनुसार सभी items की total valuation; यह Stock Valuation report में drill करता है।",
        "प्रत्येक item च्या costing method नुसार सर्व items ची total valuation; हे Stock Valuation report मध्ये drill करते.",
        "Har item ki costing method ke hisaab se sabhi items ki total valuation; ye Stock Valuation report mein drill karta hai.",
    ),
    "inventory-dashboard.fieldRules.2.name": ("Low Stock Items", "लो-स्टॉक आइटम्स", "लो-स्टॉक आयटम्स", "Low Stock Items"),
    "inventory-dashboard.fieldRules.2.description": (
        "Items at or below their reorder level; highlighted with a red border and repeated in the panel below.",
        "अपने reorder level पर या उससे नीचे के items; इन्हें red border के साथ highlight किया जाता है और नीचे panel में दोहराया जाता है।",
        "त्यांच्या reorder level वर किंवा त्याखालील items; हे red border सह highlight केले जातात आणि खालील panel मध्ये पुन्हा दाखवले जातात.",
        "Apne reorder level par ya usse neeche wale items; inhe red border ke saath highlight kiya jaata hai aur neeche panel mein repeat kiya jaata hai.",
    ),
    "inventory-dashboard.fieldRules.3.name": ("Pending Requests", "पेंडिंग रिक्वेस्ट्स", "पेंडिंग रिक्वेस्ट्स", "Pending Requests"),
    "inventory-dashboard.fieldRules.3.description": (
        "Inventory requests still awaiting a decision; drills into requester, justification and created date.",
        "वे inventory requests जो अभी भी decision का इंतज़ार कर रही हैं; यह requester, justification और created date में drill करता है।",
        "अजूनही decision ची वाट पाहत असलेल्या inventory requests; हे requester, justification आणि created date मध्ये drill करते.",
        "Wo inventory requests jo abhi bhi decision ka wait kar rahi hain; ye requester, justification aur created date mein drill karta hai.",
    ),
    "inventory-dashboard.fieldRules.4.name": ("Available Stock", "उपलब्ध स्टॉक", "उपलब्ध स्टॉक", "Available Stock"),
    "inventory-dashboard.fieldRules.4.description": (
        "On-hand quantity available across items; shares the Stock Valuation report as its drill-down source.",
        "सभी items में उपलब्ध on-hand quantity; यह अपने drill-down source के रूप में Stock Valuation report को शेयर करता है।",
        "सर्व items मध्ये उपलब्ध on-hand quantity; हे त्याच्या drill-down source म्हणून Stock Valuation report शेअर करते.",
        "Sabhi items mein available on-hand quantity; ye apne drill-down source ke roop mein Stock Valuation report share karta hai.",
    ),
    "inventory-dashboard.tip.title": (
        "Value and Available Stock drill into the same report",
        "वैल्यू और उपलब्ध स्टॉक एक ही report में drill करते हैं",
        "व्हॅल्यू आणि उपलब्ध स्टॉक एकाच report मध्ये drill करतात",
        "Value aur Available Stock ek hi report mein drill karte hain",
    ),
    "inventory-dashboard.tip.body": (
        "The \"Stock Value\" and \"Available Stock\" cards both open the Stock Valuation report — same rows, same columns. If a number looks off on one, check the other; they'll always move together since they share one data source.",
        "\"Stock Value\" और \"Available Stock\" दोनों कार्ड्स Stock Valuation report को खोलते हैं — same rows, same columns। अगर किसी एक में कोई नंबर गलत लगे, तो दूसरे को चेक करें; ये हमेशा साथ में बदलेंगे क्योंकि दोनों एक ही data source शेयर करते हैं।",
        "\"Stock Value\" आणि \"Available Stock\" ही दोन्ही कार्ड्स Stock Valuation report उघडतात — same rows, same columns. जर एखाद्या नंबरमध्ये काही चूक वाटली, तर दुसरा चेक करा; ते नेहमी एकत्र बदलतील कारण दोघेही एकच data source शेअर करतात.",
        "\"Stock Value\" aur \"Available Stock\" dono cards Stock Valuation report open karte hain — same rows, same columns. Agar kisi ek number mein kuch galat lage, to doosre ko check karein; ye hamesha saath mein move karenge kyunki dono ek hi data source share karte hain.",
    ),
}


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 INVENTORY_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(INVENTORY_DASHBOARD)} inventory-dashboard keys.")


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