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

Usage: docker compose exec api python seed_translations_pageinfo_auditor_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)
AUDITOR_DASHBOARD = {
    "auditor-dashboard.title": (
        "Auditor Dashboard",
        "ऑडिटर डैशबोर्ड",
        "ऑडिटर डॅशबोर्ड",
        "Auditor Dashboard",
    ),
    "auditor-dashboard.subtitle": (
        "Read-only compliance, custody, and governance snapshot for the Auditor role",
        "Auditor भूमिका के लिए रीड-ओनली कंप्लायंस, कस्टडी और गवर्नेंस स्नैपशॉट",
        "Auditor भूमिकेसाठी रीड-ओन्ली compliance, custody आणि governance स्नॅपशॉट",
        "Auditor role ke liye read-only compliance, custody, aur governance ka snapshot.",
    ),
    "auditor-dashboard.body.0": (
        "Compliance, audit log, and ISO 55001 readiness — read-only.",
        "कंप्लायंस, ऑडिट लॉग और ISO 55001 तैयारी — केवल पढ़ने योग्य।",
        "Compliance, audit log आणि ISO 55001 तयारी — फक्त वाचनीय (read-only).",
        "Compliance, audit log, aur ISO 55001 readiness — read-only.",
    ),
    "auditor-dashboard.body.1": (
        "This is a dedicated landing page for the Auditor role — it doesn't require the asset-manager permission the main Enterprise Dashboard needs, so Auditors always get a proper summary instead of a bare list view.",
        "यह Auditor भूमिका के लिए एक समर्पित लैंडिंग पेज है — इसमें मुख्य Enterprise Dashboard को आवश्यक asset-manager अनुमति की ज़रूरत नहीं होती, इसलिए Auditors को हमेशा एक साधारण लिस्ट व्यू के बजाय एक उचित सारांश मिलता है।",
        "हे Auditor भूमिकेसाठी एक समर्पित लँडिंग पेज आहे — मुख्य Enterprise Dashboard ला आवश्यक असलेली asset-manager परवानगी याला लागत नाही, त्यामुळे Auditors ना नेहमी साध्या list view ऐवजी योग्य सारांश मिळतो.",
        "Ye Auditor role ke liye ek dedicated landing page hai — isme main Enterprise Dashboard wali asset-manager permission ki zaroorat nahi padti, isliye Auditors ko hamesha ek bare list view ki jagah proper summary milta hai.",
    ),
    "auditor-dashboard.stepsHeading": (
        "How this page is laid out",
        "यह पेज कैसे व्यवस्थित है",
        "हे पेज कसे मांडलेले आहे",
        "Ye page kaise layout kiya gaya hai",
    ),
    "auditor-dashboard.steps.0.label": (
        "KPI cards",
        "KPI कार्ड",
        "KPI कार्ड्स",
        "KPI cards",
    ),
    "auditor-dashboard.steps.0.caption": (
        "Top row: uncustodied assets, expiring documents, warranty overrides, compliance due in 30 days.",
        "शीर्ष पंक्ति: uncustodied assets, expiring documents, warranty overrides, 30 दिनों में देय compliance।",
        "वरची रांग: uncustodied assets, expiring documents, warranty overrides, 30 दिवसांत देय compliance.",
        "Top row: uncustodied assets, expiring documents, warranty overrides, 30 din mein due compliance.",
    ),
    "auditor-dashboard.steps.1.label": (
        "Compliance by urgency",
        "अत्यावश्यकता के अनुसार कंप्लायंस",
        "तातडीनुसार compliance",
        "Urgency ke hisaab se compliance",
    ),
    "auditor-dashboard.steps.1.caption": (
        "Bar breakdown of open compliance items grouped by urgency.",
        "अत्यावश्यकता के अनुसार समूहीकृत खुले compliance आइटम का बार ब्रेकडाउन।",
        "तातडीनुसार गटबद्ध केलेल्या खुल्या compliance आयटम्सचे bar breakdown.",
        "Urgency ke hisaab se group kiye gaye open compliance items ka bar breakdown.",
    ),
    "auditor-dashboard.steps.2.label": (
        "Upcoming events",
        "आगामी इवेंट्स",
        "आगामी इव्हेंट्स",
        "Upcoming events",
    ),
    "auditor-dashboard.steps.2.caption": (
        "Compliance events due in the next 30 days, with a link into the Compliance Center.",
        "अगले 30 दिनों में देय compliance events, Compliance Center के लिंक सहित।",
        "पुढील 30 दिवसांत देय compliance events, Compliance Center च्या लिंकसह.",
        "Agle 30 dino mein due compliance events, Compliance Center ke link ke saath.",
    ),
    "auditor-dashboard.steps.3.label": (
        "Audit log summary",
        "ऑडिट लॉग सारांश",
        "Audit log सारांश",
        "Audit log summary",
    ),
    "auditor-dashboard.steps.3.caption": (
        "Daily count of audit-log events for the most recent days.",
        "हाल के दिनों के लिए audit-log events की दैनिक गिनती।",
        "अलीकडील दिवसांसाठी audit-log events ची दैनंदिन संख्या.",
        "Recent dino ke liye audit-log events ka daily count.",
    ),
    "auditor-dashboard.steps.4.label": (
        "Governance score",
        "गवर्नेंस स्कोर",
        "Governance score",
        "Governance score",
    ),
    "auditor-dashboard.steps.4.caption": (
        "ISO 55001 readiness percentage, with a link to the full readiness report.",
        "ISO 55001 तैयारी प्रतिशत, पूर्ण readiness report के लिंक सहित।",
        "ISO 55001 तयारीची टक्केवारी, संपूर्ण readiness report च्या लिंकसह.",
        "ISO 55001 readiness percentage, full readiness report ke link ke saath.",
    ),
    "auditor-dashboard.fieldRules.0.name": (
        "Uncustodied Assets",
        "Uncustodied Assets",
        "Uncustodied Assets",
        "Uncustodied Assets",
    ),
    "auditor-dashboard.fieldRules.0.description": (
        "Assets with no current custodian on record — a custody gap the organization should close.",
        "ऐसे assets जिनके रिकॉर्ड में कोई मौजूदा custodian नहीं है — एक custody gap जिसे संगठन को बंद करना चाहिए।",
        "ज्या assets च्या रेकॉर्डमध्ये सध्याचा custodian नाही — एक custody gap जो संस्थेने बंद करायला हवा.",
        "Wo assets jinke record mein koi current custodian nahi hai — ek custody gap jise organization ko close karna chahiye.",
    ),
    "auditor-dashboard.fieldRules.1.name": (
        "Expiring Documents",
        "समाप्त होने वाले दस्तावेज़",
        "मुदत संपणारी कागदपत्रे",
        "Expiring Documents",
    ),
    "auditor-dashboard.fieldRules.1.description": (
        "Warranty, insurance, and AMC documents nearing their expiry date.",
        "Warranty, insurance और AMC दस्तावेज़ जो अपनी expiry date के करीब हैं।",
        "Warranty, insurance आणि AMC कागदपत्रे जी त्यांच्या expiry date जवळ आली आहेत.",
        "Warranty, insurance, aur AMC documents jo apni expiry date ke kareeb hain.",
    ),
    "auditor-dashboard.fieldRules.2.name": (
        "Warranty Overrides",
        "वारंटी ओवरराइड",
        "Warranty overrides",
        "Warranty Overrides",
    ),
    "auditor-dashboard.fieldRules.2.description": (
        "Count of manual warranty-status overrides recorded — a common audit flag.",
        "दर्ज किए गए मैनुअल warranty-status overrides की गिनती — एक सामान्य audit flag।",
        "नोंदवलेल्या manual warranty-status overrides ची संख्या — एक सामान्य audit flag.",
        "Record kiye gaye manual warranty-status overrides ka count — ek common audit flag.",
    ),
    "auditor-dashboard.fieldRules.3.name": (
        "Compliance Due (30d)",
        "कंप्लायंस देय (30 दिन)",
        "Compliance देय (30 दिवस)",
        "Compliance Due (30d)",
    ),
    "auditor-dashboard.fieldRules.3.description": (
        "Compliance events (renewals, filings, inspections) due within the next 30 days.",
        "अगले 30 दिनों के भीतर देय compliance events (renewals, filings, inspections)।",
        "पुढील 30 दिवसांत देय compliance events (renewals, filings, inspections).",
        "Agle 30 dino ke andar due compliance events (renewals, filings, inspections).",
    ),
    "auditor-dashboard.fieldRules.4.name": (
        "ISO 55001 Score",
        "ISO 55001 स्कोर",
        "ISO 55001 Score",
        "ISO 55001 Score",
    ),
    "auditor-dashboard.fieldRules.4.description": (
        "Organization-wide readiness percentage against ISO 55001 asset-management criteria.",
        "ISO 55001 asset-management मानदंडों के विरुद्ध संगठन-व्यापी तैयारी प्रतिशत।",
        "ISO 55001 asset-management निकषांविरुद्ध संस्था-व्यापी तयारीची टक्केवारी.",
        "ISO 55001 asset-management criteria ke against organization-wide readiness percentage.",
    ),
    "auditor-dashboard.tip.title": (
        "Audit Log Summary is a snapshot, not the full trail",
        "Audit Log Summary एक स्नैपशॉट है, पूरा trail नहीं",
        "Audit Log Summary हा एक स्नॅपशॉट आहे, संपूर्ण trail नाही",
        "Audit Log Summary ek snapshot hai, poora trail nahi",
    ),
    "auditor-dashboard.tip.body": (
        "This panel only shows the most recent 7 days of activity counts. For the complete, filterable event history, open Audit Timeline under Governance & Compliance — this widget is a quick pulse-check, not a substitute for it.",
        "यह पैनल केवल पिछले 7 दिनों की activity counts दिखाता है। पूर्ण, filterable event history के लिए, Governance & Compliance के अंतर्गत Audit Timeline खोलें — यह widget एक त्वरित pulse-check है, इसका विकल्प नहीं।",
        "हे पॅनेल फक्त मागील 7 दिवसांच्या activity counts दाखवते. संपूर्ण, filterable event history साठी, Governance & Compliance अंतर्गत Audit Timeline उघडा — हा widget एक जलद pulse-check आहे, त्याचा पर्याय नाही.",
        "Ye panel sirf pichhle 7 din ke activity counts dikhata hai. Complete, filterable event history ke liye, Governance & Compliance ke andar Audit Timeline kholein — ye widget ek quick pulse-check hai, iska substitute 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 AUDITOR_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(AUDITOR_DASHBOARD)} auditor-dashboard keys.")


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