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

Usage: docker compose exec api python seed_translations_pageinfo_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)
DASHBOARD = {
    "dashboard.title": (
        "Enterprise Dashboard",
        "एंटरप्राइज़ डैशबोर्ड",
        "एंटरप्राइझ डॅशबोर्ड",
        "Enterprise Dashboard",
    ),
    "dashboard.subtitle": (
        "Your organization's live asset, custody, and compliance snapshot",
        "आपके संगठन का लाइव asset, custody और compliance स्नैपशॉट",
        "तुमच्या संस्थेचा लाइव्ह asset, custody आणि compliance स्नॅपशॉट",
        "Aapki organization ka live asset, custody, aur compliance snapshot.",
    ),
    "dashboard.body.0": (
        "This is your starting screen — a quick summary of assets, alerts, and activity across the organization.",
        "यह आपकी शुरुआती स्क्रीन है — पूरे संगठन में assets, अलर्ट और गतिविधि का त्वरित सारांश।",
        "ही तुमची सुरुवातीची स्क्रीन आहे — संपूर्ण संस्थेतील assets, अलर्ट्स आणि activity चा जलद सारांश.",
        "Ye aapki starting screen hai — poori organization ke assets, alerts, aur activity ka quick summary.",
    ),
    "dashboard.body.1": (
        "Use the cards and charts here to spot problems early, then drill into the relevant module for details.",
        "समस्याओं को जल्दी पहचानने के लिए यहाँ के cards और charts का उपयोग करें, फिर विवरण के लिए संबंधित module में जाएँ।",
        "समस्या लवकर ओळखण्यासाठी येथील cards आणि charts वापरा, नंतर तपशीलांसाठी संबंधित module मध्ये जा.",
        "Problems jaldi spot karne ke liye yahan ke cards aur charts use karein, phir details ke liye relevant module mein drill karein.",
    ),
    "dashboard.body.2": (
        "Every widget reads live data — the asset totals, lifecycle chart, and recent activity feed refresh from the same numbers you'd see in the underlying modules.",
        "हर widget लाइव डेटा पढ़ता है — asset totals, lifecycle chart और recent activity feed उन्हीं आँकड़ों से refresh होते हैं जो आपको underlying modules में दिखते हैं।",
        "प्रत्येक widget लाइव्ह डेटा वाचतो — asset totals, lifecycle chart आणि recent activity feed त्याच आकड्यांवरून refresh होतात जे तुम्हाला underlying modules मध्ये दिसतात.",
        "Har widget live data read karta hai — asset totals, lifecycle chart, aur recent activity feed unhi numbers se refresh hote hain jo aapko underlying modules mein dikhte hain.",
    ),
    "dashboard.stepsHeading": (
        "How this page is laid out",
        "यह पेज कैसे व्यवस्थित है",
        "हे पेज कसे मांडलेले आहे",
        "Ye page kaise laid out hai",
    ),
    "dashboard.steps.0.label": (
        "KPI cards",
        "KPI कार्ड्स",
        "KPI कार्ड्स",
        "KPI cards",
    ),
    "dashboard.steps.0.caption": (
        "Top row: total assets, custody gaps, maintenance flags, and tag coverage.",
        "ऊपरी पंक्ति: total assets, custody gaps, maintenance flags और tag coverage।",
        "वरची रांग: total assets, custody gaps, maintenance flags आणि tag coverage.",
        "Top row: total assets, custody gaps, maintenance flags, aur tag coverage.",
    ),
    "dashboard.steps.1.label": (
        "Lifecycle distribution",
        "Lifecycle वितरण",
        "Lifecycle वितरण",
        "Lifecycle distribution",
    ),
    "dashboard.steps.1.caption": (
        "Bar breakdown of every asset by its current lifecycle state.",
        "हर asset का उसकी वर्तमान lifecycle स्थिति के अनुसार bar breakdown।",
        "प्रत्येक asset चे त्याच्या सद्य lifecycle स्थितीनुसार bar breakdown.",
        "Har asset ka uski current lifecycle state ke hisaab se bar breakdown.",
    ),
    "dashboard.steps.2.label": (
        "Recent activity",
        "हाल की गतिविधि",
        "अलीकडील activity",
        "Recent activity",
    ),
    "dashboard.steps.2.caption": (
        "Your last 5 audit-log events, with a link to the full log.",
        "आपके पिछले 5 audit-log events, पूरे log के लिंक के साथ।",
        "तुमचे शेवटचे 5 audit-log events, संपूर्ण log च्या लिंकसह.",
        "Aapke last 5 audit-log events, full log ke link ke saath.",
    ),
    "dashboard.steps.3.label": (
        "Maintenance & governance panel",
        "Maintenance और governance पैनल",
        "Maintenance आणि governance पॅनल",
        "Maintenance & governance panel",
    ),
    "dashboard.steps.3.caption": (
        "Assets due for maintenance, plus the ISO 55001 readiness score.",
        "maintenance के लिए देय assets, साथ ही ISO 55001 readiness score।",
        "maintenance साठी देय असलेल्या assets, तसेच ISO 55001 readiness score.",
        "Maintenance ke liye due assets, plus ISO 55001 readiness score.",
    ),
    "dashboard.fieldRules.0.name": (
        "Total Assets Tracked",
        "कुल ट्रैक किए गए Assets",
        "एकूण ट्रॅक केलेली Assets",
        "Total Assets Tracked",
    ),
    "dashboard.fieldRules.0.description": (
        "Count of every asset in the register, across all lifecycle states.",
        "register में मौजूद हर asset की गिनती, सभी lifecycle states में।",
        "register मधील प्रत्येक asset ची मोजणी, सर्व lifecycle states मध्ये.",
        "Register mein maujood har asset ki count, saare lifecycle states mein.",
    ),
    "dashboard.fieldRules.1.name": (
        "Custody Gaps",
        "Custody Gaps",
        "Custody Gaps",
        "Custody Gaps",
    ),
    "dashboard.fieldRules.1.description": (
        "Assets with no current custodian assigned — needs a custody transfer to clear.",
        "वे assets जिनका कोई वर्तमान custodian assign नहीं है — इसे clear करने के लिए custody transfer ज़रूरी है।",
        "ज्या assets साठी सध्या कोणताही custodian assign केलेला नाही — हे clear करण्यासाठी custody transfer आवश्यक आहे.",
        "Jin assets ka koi current custodian assign nahi hai — inhe clear karne ke liye custody transfer chahiye.",
    ),
    "dashboard.fieldRules.2.name": (
        "Assets Needing Maintenance",
        "Maintenance की आवश्यकता वाले Assets",
        "Maintenance आवश्यक असलेली Assets",
        "Assets Needing Maintenance",
    ),
    "dashboard.fieldRules.2.description": (
        "Assets flagged by the upcoming-maintenance widget; shows 0 if you lack the maintenance permission.",
        "upcoming-maintenance widget द्वारा flag किए गए assets; यदि आपके पास maintenance permission नहीं है तो 0 दिखाता है।",
        "upcoming-maintenance widget द्वारे flag केलेली assets; तुमच्याकडे maintenance permission नसल्यास 0 दाखवते.",
        "Upcoming-maintenance widget dwara flag ki gayi assets; agar aapke paas maintenance permission nahi hai to 0 dikhata hai.",
    ),
    "dashboard.fieldRules.3.name": (
        "Tag Coverage",
        "Tag Coverage",
        "Tag Coverage",
        "Tag Coverage",
    ),
    "dashboard.fieldRules.3.description": (
        "Percentage of assets that have a physical tag/QR code affixed and scanned.",
        "उन assets का प्रतिशत जिन पर physical tag/QR code लगाया और scan किया गया है।",
        "ज्या assets वर physical tag/QR code लावलेला आणि scan केलेला आहे त्यांची टक्केवारी.",
        "Un assets ka percentage jinpar physical tag/QR code laga hua aur scan kiya gaya hai.",
    ),
    "dashboard.tip.title": (
        "Missing widgets aren't a bug",
        "गायब widgets कोई bug नहीं हैं",
        "गहाळ widgets हा bug नाही",
        "Missing widgets koi bug nahi hain",
    ),
    "dashboard.tip.body": (
        "The Governance Score panel and the Assets Needing Maintenance list only load if your role has the auditor_dashboard / maintenance permissions. If your role lacks them, the page hides those cards instead of failing to load — the rest of the dashboard still works.",
        "Governance Score पैनल और Assets Needing Maintenance सूची तभी load होती है जब आपकी role के पास auditor_dashboard / maintenance permissions हों। यदि आपकी role के पास ये नहीं हैं, तो पेज load होने में विफल होने के बजाय उन cards को छिपा देता है — बाकी dashboard फिर भी काम करता रहता है।",
        "Governance Score पॅनल आणि Assets Needing Maintenance यादी फक्त तेव्हाच load होते जेव्हा तुमच्या role कडे auditor_dashboard / maintenance permissions असतात. जर तुमच्या role कडे ते नसतील, तर पेज load होण्यात अयशस्वी होण्याऐवजी ती cards लपवते — उर्वरित dashboard तरीही काम करत राहते.",
        "Governance Score panel aur Assets Needing Maintenance list tabhi load hoti hai jab aapki role ke paas auditor_dashboard / maintenance permissions hon. Agar aapki role ke paas ye nahi hain, to page fail hone ke bajaye un cards ko hide kar deta hai — baaki dashboard phir bhi kaam karta rehta 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 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(DASHBOARD)} dashboard keys.")


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