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

Usage: docker compose exec api python seed_translations_pageinfo_document_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)
DOCUMENT_DASHBOARD = {
    "document-dashboard.title": (
        "Document Intelligence",
        "दस्तावेज़ इंटेलिजेंस",
        "दस्तावेज इंटेलिजन्स",
        "Document Intelligence",
    ),
    "document-dashboard.subtitle": (
        "A read-only health snapshot of the document register — expiry, OCR coverage, and external sync.",
        "दस्तावेज़ रजिस्टर का एक रीड-ओनली हेल्थ स्नैपशॉट — expiry, OCR coverage, और external sync।",
        "दस्तावेज रजिस्टरचा एक रीड-ओन्ली हेल्थ स्नॅपशॉट — expiry, OCR coverage, आणि external sync.",
        "Document register ka ek read-only health snapshot — expiry, OCR coverage, aur external sync.",
    ),
    "document-dashboard.body.0": (
        "This dashboard summarizes the whole document register: how many documents are active, expiring, overdue, or archived, and how much of it has been OCR'd for full-text search.",
        "यह dashboard पूरे document register को संक्षेप में दिखाता है: कितने documents active, expiring, overdue, या archived हैं, और उनमें से कितने full-text search के लिए OCR किए जा चुके हैं।",
        "हे dashboard संपूर्ण document register चा सारांश दाखवते: किती documents active, expiring, overdue, किंवा archived आहेत, आणि त्यापैकी किती full-text search साठी OCR केले गेले आहेत.",
        "Ye dashboard poore document register ka summary dikhata hai: kitne documents active, expiring, overdue, ya archived hain, aur unmein se kitne full-text search ke liye OCR ho chuke hain.",
    ),
    "document-dashboard.body.1": (
        "It's a summary, not a workspace — use the quick actions or the buttons at the top to jump into the Document Repository or the Expiry & Renewal Center to actually upload, renew, or archive a document.",
        "यह एक सारांश है, workspace नहीं — किसी document को वास्तव में upload, renew, या archive करने के लिए ऊपर दिए गए quick actions या buttons का उपयोग करके Document Repository या Expiry & Renewal Center पर जाएँ।",
        "हे एक सारांश आहे, workspace नाही — एखादी document प्रत्यक्षात upload, renew, किंवा archive करण्यासाठी वर दिलेल्या quick actions किंवा buttons चा वापर करून Document Repository किंवा Expiry & Renewal Center वर जा.",
        "Ye ek summary hai, workspace nahi — kisi document ko actually upload, renew, ya archive karne ke liye upar diye gaye quick actions ya buttons ka use karke Document Repository ya Expiry & Renewal Center par jaayein.",
    ),
    "document-dashboard.stepsHeading": (
        "How this page is laid out",
        "यह पेज कैसे व्यवस्थित है",
        "हे पेज कसे मांडलेले आहे",
        "Ye page kaise laid out hai",
    ),
    "document-dashboard.steps.0.label": ("Summary KPIs", "सारांश KPIs", "सारांश KPIs", "Summary KPIs"),
    "document-dashboard.steps.0.caption": (
        "Total, Active, Expiring, Overdue, and Archived document counts.",
        "Total, Active, Expiring, Overdue, और Archived document की गिनती।",
        "Total, Active, Expiring, Overdue, आणि Archived document ची संख्या.",
        "Total, Active, Expiring, Overdue, aur Archived document counts.",
    ),
    "document-dashboard.steps.1.label": (
        "Telemetry & breakdowns",
        "टेलीमेट्री और ब्रेकडाउन",
        "टेलीमेट्री आणि ब्रेकडाउन",
        "Telemetry aur breakdowns",
    ),
    "document-dashboard.steps.1.caption": (
        "Expiring-this-month, virus-flagged, renewals pending, recent uploads, plus category/department splits.",
        "इस महीने expire होने वाले, virus-flagged, pending renewals, हाल के uploads, साथ ही category/department के अनुसार विभाजन।",
        "या महिन्यात expire होणारे, virus-flagged, pending renewals, अलीकडील uploads, तसेच category/department नुसार विभागणी.",
        "Is mahine expire hone wale, virus-flagged, pending renewals, recent uploads, plus category/department ke hisaab se splits.",
    ),
    "document-dashboard.steps.2.label": ("OCR Coverage", "OCR कवरेज", "OCR कव्हरेज", "OCR Coverage"),
    "document-dashboard.steps.2.caption": (
        "Pie chart of how much of the register has had text extracted for search.",
        "यह दर्शाने वाला pie chart कि register में से कितने हिस्से का text search के लिए extract किया जा चुका है।",
        "register पैकी किती भागाचा text search साठी extract केला गेला आहे हे दाखवणारा pie chart.",
        "Pie chart jo dikhata hai ki register mein se kitne hisse ka text search ke liye extract ho chuka hai.",
    ),
    "document-dashboard.steps.3.label": ("SharePoint Sync", "SharePoint सिंक", "SharePoint सिंक", "SharePoint Sync"),
    "document-dashboard.steps.3.caption": (
        "Push the register out to an external SharePoint library (admin only).",
        "register को external SharePoint library में push करें (केवल admin के लिए)।",
        "register ला external SharePoint library मध्ये push करा (फक्त admin साठी).",
        "Register ko external SharePoint library mein push karein (sirf admin ke liye).",
    ),
    "document-dashboard.fieldRules.0.name": ("Overdue", "ओवरड्यू", "ओव्हरड्यू", "Overdue"),
    "document-dashboard.fieldRules.0.description": (
        "Documents past their expiry date with no renewal recorded yet — highest priority.",
        "ऐसे documents जिनकी expiry date निकल चुकी है और अभी तक कोई renewal दर्ज नहीं हुआ है — सर्वोच्च प्राथमिकता।",
        "ज्या documents ची expiry date उलटून गेली आहे आणि अद्याप कोणतेही renewal नोंदवले गेलेले नाही — सर्वोच्च प्राधान्य.",
        "Wo documents jinki expiry date nikal chuki hai aur abhi tak koi renewal record nahi hua hai — highest priority.",
    ),
    "document-dashboard.fieldRules.1.name": ("Virus-Flagged", "वायरस-फ़्लैग्ड", "व्हायरस-फ्लॅग्ड", "Virus-Flagged"),
    "document-dashboard.fieldRules.1.description": (
        "Uploads the malware scan flagged as high-risk; review before trusting the file.",
        "वे uploads जिन्हें malware scan ने high-risk के रूप में flag किया है; file पर भरोसा करने से पहले review करें।",
        "जे uploads malware scan ने high-risk म्हणून flag केले आहेत; file वर विश्वास ठेवण्यापूर्वी review करा.",
        "Wo uploads jinhe malware scan ne high-risk flag kiya hai; file par trust karne se pehle review karein.",
    ),
    "document-dashboard.fieldRules.2.name": ("OCR Coverage %", "OCR कवरेज %", "OCR कव्हरेज %", "OCR Coverage %"),
    "document-dashboard.fieldRules.2.description": (
        "Share of documents with extracted text. Low coverage means many files won't surface in full-text search.",
        "extracted text वाले documents का हिस्सा। कम coverage का मतलब है कि कई files full-text search में सामने नहीं आएँगी।",
        "extracted text असलेल्या documents चा वाटा. कमी coverage म्हणजे अनेक files full-text search मध्ये दिसणार नाहीत.",
        "Extracted text wale documents ka share. Kam coverage ka matlab hai ki kai files full-text search mein nahi dikhengi.",
    ),
    "document-dashboard.fieldRules.3.name": ("Quick Actions", "क्विक एक्शन्स", "क्विक अ‍ॅक्शन्स", "Quick Actions"),
    "document-dashboard.fieldRules.3.description": (
        "Buttons shown here reflect your own permission grants, returned by the API — not a client-side role guess.",
        "यहाँ दिखाए गए buttons आपकी अपनी permission grants को दर्शाते हैं, जो API द्वारा लौटाई जाती हैं — client-side role guess नहीं।",
        "इथे दाखवलेले buttons तुमच्या स्वतःच्या permission grants दर्शवतात, जे API द्वारे परत केले जातात — client-side role guess नाही.",
        "Yahan dikhaye gaye buttons aapke apne permission grants ko reflect karte hain, jo API se return hote hain — client-side role guess nahi.",
    ),
    "document-dashboard.tip.title": (
        "SharePoint Sync is a stub",
        "SharePoint Sync एक stub है",
        "SharePoint Sync हे एक stub आहे",
        "SharePoint Sync ek stub hai",
    ),
    "document-dashboard.tip.body": (
        "\"Sync Now\" doesn't push any files yet — the backend always answers with a contract preview (required fields, expected status) so integrators can see what a real sync call will need. No documents leave the system today.",
        "\"Sync Now\" अभी तक कोई files push नहीं करता — backend हमेशा एक contract preview (required fields, expected status) के साथ जवाब देता है ताकि integrators देख सकें कि एक असली sync call में क्या चाहिए होगा। आज कोई भी document system से बाहर नहीं जाता।",
        "\"Sync Now\" अजून कोणत्याही files push करत नाही — backend नेहमी एक contract preview (required fields, expected status) सह उत्तर देतो जेणेकरून integrators ना कळेल की खऱ्या sync call साठी काय लागेल. आज कोणतीही document system मधून बाहेर जात नाही.",
        "\"Sync Now\" abhi tak koi files push nahi karta — backend hamesha ek contract preview (required fields, expected status) ke saath jawab deta hai taaki integrators dekh sakein ki ek real sync call mein kya chahiye hoga. Aaj koi bhi document system se bahar nahi jaata.",
    ),
}


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 DOCUMENT_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(DOCUMENT_DASHBOARD)} document-dashboard keys.")


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