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

Usage: docker compose exec api python seed_translations_pageinfo_audit_history_registry.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)
AUDIT_HISTORY_REGISTRY = {
    "audit-history-registry.title": (
        "Audit History Registry",
        "ऑडिट हिस्ट्री रजिस्टर",
        "ऑडिट हिस्ट्री रजिस्टर",
        "Audit History Registry",
    ),
    "audit-history-registry.subtitle": (
        "Searchable, tamper-evident log of every action taken in the system",
        "सिस्टम में की गई हर कार्रवाई का खोजने योग्य, छेड़छाड़-रोधी लॉग",
        "सिस्टममध्ये केलेल्या प्रत्येक कृतीचा शोधण्यायोग्य, छेडछाड-प्रतिरोधक लॉग",
        "System mein ki gayi har action ka searchable, tamper-evident log.",
    ),
    "audit-history-registry.body.0": (
        "A paged, searchable record of every audit log event — who did what, to which resource, and when — with the exact before/after state captured for each change.",
        "हर audit log event का paged, खोजने योग्य रिकॉर्ड — किसने क्या किया, किस resource पर, और कब — साथ ही हर बदलाव के लिए captured किया गया exact before/after state।",
        "प्रत्येक audit log event चा paged, शोधण्यायोग्य रेकॉर्ड — कोणी काय केले, कोणत्या resource वर, आणि केव्हा — प्रत्येक बदलासाठी capture केलेल्या exact before/after state सह.",
        "Har audit log event ka paged, searchable record — kisne kya kiya, kis resource par, aur kab — har change ke liye capture kiya gaya exact before/after state ke saath.",
    ),
    "audit-history-registry.body.1": (
        "Search only matches the action, resource type, or resource ID; it does not search by user name or by the contents of the before/after state.",
        "Search केवल action, resource type, या resource ID से मेल खाती है; यह user name से या before/after state की सामग्री से खोज नहीं करती।",
        "Search फक्त action, resource type, किंवा resource ID शी जुळते; ती user name ने किंवा before/after state च्या मजकुराने शोध घेत नाही.",
        "Search sirf action, resource type, ya resource ID se match karti hai; ye user name se ya before/after state ke content se search nahi karti.",
    ),
    "audit-history-registry.stepsHeading": (
        "How an event gets here",
        "कोई event यहाँ कैसे पहुँचता है",
        "एखादी event इथे कशी येते",
        "Ek event yahan kaise pahunchta hai",
    ),
    "audit-history-registry.steps.0.label": ("Event Logged", "Event लॉग हुआ", "Event लॉग झाली", "Event Logged"),
    "audit-history-registry.steps.0.caption": (
        "Every create/update/delete/login action across the system writes one row automatically.",
        "पूरे सिस्टम में हर create/update/delete/login action अपने आप एक row लिखता है।",
        "संपूर्ण सिस्टममध्ये प्रत्येक create/update/delete/login action आपोआप एक row लिहिते.",
        "Poore system mein har create/update/delete/login action apne aap ek row likhta hai.",
    ),
    "audit-history-registry.steps.1.label": ("Hash-Chained", "Hash-Chained", "Hash-Chained", "Hash-Chained"),
    "audit-history-registry.steps.1.caption": (
        "Each row's hash embeds the previous row's hash, so a silently edited row breaks the chain from that point on.",
        "हर row का hash पिछली row के hash को embed करता है, इसलिए चुपचाप edit की गई row उस बिंदु से chain को तोड़ देती है।",
        "प्रत्येक row चा hash आधीच्या row च्या hash ला embed करतो, त्यामुळे शांतपणे edit केलेली row त्या बिंदूपासून chain तोडते.",
        "Har row ka hash pichli row ke hash ko embed karta hai, isliye silently edit hui row us point se chain ko break kar deti hai.",
    ),
    "audit-history-registry.steps.2.label": ("Reviewed", "समीक्षा की गई", "पुनरावलोकन केले", "Reviewed"),
    "audit-history-registry.steps.2.caption": (
        "Click the eye icon to inspect the exact before/after JSON captured for that action.",
        "उस action के लिए captured exact before/after JSON देखने के लिए eye icon पर क्लिक करें।",
        "त्या action साठी capture केलेला exact before/after JSON पाहण्यासाठी eye icon वर क्लिक करा.",
        "Us action ke liye capture hua exact before/after JSON dekhne ke liye eye icon par click karein.",
    ),
    "audit-history-registry.steps.3.label": ("Exported", "एक्सपोर्ट किया गया", "एक्सपोर्ट केले", "Exported"),
    "audit-history-registry.steps.3.caption": (
        "Download a sanitized (PII-stripped) copy of the Assets or Custody audit trail as JSON.",
        "Assets या Custody audit trail की sanitized (PII-रहित) कॉपी JSON के रूप में डाउनलोड करें।",
        "Assets किंवा Custody audit trail ची sanitized (PII-रहित) प्रत JSON स्वरूपात डाउनलोड करा.",
        "Assets ya Custody audit trail ki sanitized (PII-stripped) copy JSON format mein download karein.",
    ),
    "audit-history-registry.fieldRules.0.name": ("Action", "Action", "Action", "Action"),
    "audit-history-registry.fieldRules.0.description": (
        "Humanized name of what happened (e.g. \"Asset Updated\"), derived from the raw backend event code.",
        "जो हुआ उसका humanized नाम (जैसे \"Asset Updated\"), raw backend event code से प्राप्त किया गया।",
        "जे घडले त्याचे humanized नाव (उदा. \"Asset Updated\"), raw backend event code वरून काढलेले.",
        "Jo hua uska humanized naam (jaise \"Asset Updated\"), raw backend event code se derive kiya gaya.",
    ),
    "audit-history-registry.fieldRules.1.name": ("Resource", "Resource", "Resource", "Resource"),
    "audit-history-registry.fieldRules.1.description": (
        "Entity type and ID affected, with a friendly name resolved for the rows on the current page.",
        "प्रभावित entity type और ID, वर्तमान page की rows के लिए resolve किए गए friendly नाम के साथ।",
        "प्रभावित झालेला entity type आणि ID, सध्याच्या page वरील rows साठी resolve केलेल्या friendly नावासह.",
        "Affected entity type aur ID, current page ki rows ke liye resolve kiya gaya friendly naam ke saath.",
    ),
    "audit-history-registry.fieldRules.2.name": ("Status", "Status", "Status", "Status"),
    "audit-history-registry.fieldRules.2.description": (
        "HTTP status of the underlying API call; codes 500 and above are flagged red as server errors.",
        "अंतर्निहित API call का HTTP status; 500 और उससे ऊपर के codes को server errors के रूप में लाल रंग में फ़्लैग किया जाता है।",
        "अंतर्निहित API call चा HTTP status; 500 आणि त्यावरील codes server errors म्हणून लाल रंगात फ्लॅग केले जातात.",
        "Underlying API call ka HTTP status; 500 aur usse upar ke codes server errors ke roop mein red flag hote hain.",
    ),
    "audit-history-registry.fieldRules.3.name": ("Seq", "Seq", "Seq", "Seq"),
    "audit-history-registry.fieldRules.3.description": (
        "Monotonic sequence number used to verify the tamper-evident hash chain hasn't been broken.",
        "यह सत्यापित करने के लिए इस्तेमाल होने वाला monotonic sequence number कि tamper-evident hash chain टूटी तो नहीं है।",
        "tamper-evident hash chain तुटली नाही याची पडताळणी करण्यासाठी वापरला जाणारा monotonic sequence number.",
        "Ye verify karne ke liye use hone wala monotonic sequence number ki tamper-evident hash chain toota to nahi hai.",
    ),
    "audit-history-registry.fieldRules.4.name": ("Export table", "Export table", "Export table", "Export table"),
    "audit-history-registry.fieldRules.4.description": (
        "Chooses which whitelisted dataset (Assets or Custody) the sanitized export pulls from — there's no \"export everything\" option.",
        "यह तय करता है कि sanitized export किस whitelisted dataset (Assets या Custody) से लिया जाए — कोई \"export everything\" विकल्प नहीं है।",
        "sanitized export कोणत्या whitelisted dataset (Assets किंवा Custody) मधून घ्यायचा हे ठरवते — \"export everything\" असा पर्याय नाही.",
        "Ye decide karta hai ki sanitized export kis whitelisted dataset (Assets ya Custody) se liya jaaye — koi \"export everything\" option nahi hai.",
    ),
    "audit-history-registry.tip.title": (
        "This page doesn't verify the chain",
        "यह page chain को verify नहीं करता",
        "हे page chain verify करत नाही",
        "Ye page chain verify nahi karta",
    ),
    "audit-history-registry.tip.body": (
        "The hash column shows each event's hash but doesn't check it against the previous row. To actually confirm nothing was tampered with, go to Asset Management → Tag Verification and click \"Run Tamper Check\" — it walks the full chain and reports the first sequence number where it breaks, if any.",
        "Hash column हर event का hash दिखाता है लेकिन इसे पिछली row के विरुद्ध check नहीं करता। यह पक्का पुष्टि करने के लिए कि कुछ भी tamper नहीं हुआ है, Asset Management → Tag Verification पर जाएँ और \"Run Tamper Check\" पर क्लिक करें — यह पूरी chain को walk करता है और वह पहला sequence number बताता है जहाँ (यदि कोई हो) यह टूटती है।",
        "Hash column प्रत्येक event चा hash दाखवते पण तो आधीच्या row विरुद्ध check करत नाही. काहीही tamper झाले नाही याची खरी खात्री करण्यासाठी, Asset Management → Tag Verification वर जा आणि \"Run Tamper Check\" वर क्लिक करा — ते संपूर्ण chain walk करते आणि chain कुठे (असल्यास) तुटते ते पहिले sequence number सांगते.",
        "Hash column har event ka hash dikhata hai lekin usse pichli row ke against check nahi karta. Ye actually confirm karne ke liye ki kuch bhi tamper nahi hua, Asset Management → Tag Verification par jaayein aur \"Run Tamper Check\" par click karein — ye poori chain ko walk karta hai aur pehla sequence number batata hai jahan (agar koi ho) ye break hoti 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 AUDIT_HISTORY_REGISTRY.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(AUDIT_HISTORY_REGISTRY)} audit-history-registry keys.")


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