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

Usage: docker compose exec api python seed_translations_pageinfo_audit_timeline.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_TIMELINE = {
    "audit-timeline.title": (
        "Audit Timeline",
        "ऑडिट टाइमलाइन",
        "ऑडिट टाइमलाइन",
        "Audit Timeline",
    ),
    "audit-timeline.subtitle": (
        "The complete, tamper-evident history of who did what",
        "किसने क्या किया, इसका पूरा और छेड़छाड़-रोधी इतिहास",
        "कोणी काय केले याचा संपूर्ण आणि छेडछाड-रोधी इतिहास",
        "Kisne kya kiya, iska complete aur tamper-evident history",
    ),
    "audit-timeline.body.0": (
        "Every write in the system — create, update, delete, approve — is recorded here as an immutable event: who did it, when, and on which resource. Use the dropdown to narrow the feed to one resource type at a time.",
        "सिस्टम में हर write — create, update, delete, approve — यहाँ एक immutable event के रूप में दर्ज किया जाता है: किसने किया, कब किया, और किस resource पर किया। एक बार में एक resource type तक feed को सीमित करने के लिए dropdown का उपयोग करें।",
        "सिस्टममधील प्रत्येक write — create, update, delete, approve — येथे एक immutable event म्हणून नोंदवला जातो: कोणी केले, कधी केले, आणि कोणत्या resource वर केले. एका वेळी एका resource type पर्यंत feed मर्यादित करण्यासाठी dropdown वापरा.",
        "System mein har write — create, update, delete, approve — yahan ek immutable event ke roop mein record hota hai: kisne kiya, kab kiya, aur kis resource par kiya. Ek time mein feed ko ek resource type tak narrow karne ke liye dropdown use karein.",
    ),
    "audit-timeline.body.1": (
        "This view shows only the latest 100 events; there's no server-side date or user filter yet, so it's best for a quick recent-activity check rather than a deep historical search.",
        "यह view केवल नवीनतम 100 events दिखाता है; अभी तक कोई server-side date या user filter नहीं है, इसलिए यह गहरी historical search के बजाय एक त्वरित recent-activity जाँच के लिए सबसे उपयुक्त है।",
        "हे view फक्त नवीनतम 100 events दाखवते; अजून कोणतेही server-side date किंवा user filter नाही, त्यामुळे हे सखोल historical search ऐवजी जलद recent-activity तपासणीसाठी सर्वोत्तम आहे.",
        "Ye view sirf latest 100 events dikhata hai; abhi tak koi server-side date ya user filter nahi hai, isliye ye deep historical search ke bajaye ek quick recent-activity check ke liye best hai.",
    ),
    "audit-timeline.stepsHeading": (
        "How each entry is secured",
        "हर entry कैसे सुरक्षित की जाती है",
        "प्रत्येक entry कशी सुरक्षित केली जाते",
        "Har entry kaise secure ki jaati hai",
    ),
    "audit-timeline.steps.0.label": ("Event Occurs", "Event होता है", "Event घडते", "Event Occurs"),
    "audit-timeline.steps.0.caption": (
        "A user or system action writes to an audited table",
        "एक user या system action किसी audited table में लिखता है",
        "एक user किंवा system action एखाद्या audited table मध्ये लिहितो",
        "Ek user ya system action kisi audited table mein likhta hai",
    ),
    "audit-timeline.steps.1.label": ("Sequenced", "Sequenced किया गया", "Sequenced केले जाते", "Sequenced"),
    "audit-timeline.steps.1.caption": (
        "Assigned the next sequence number in order",
        "क्रम में अगला sequence number दिया जाता है",
        "क्रमाने पुढील sequence number दिला जातो",
        "Order mein agla sequence number assign kiya jaata hai",
    ),
    "audit-timeline.steps.2.label": ("Hash-Chained", "Hash-Chained किया गया", "Hash-Chained केले जाते", "Hash-Chained"),
    "audit-timeline.steps.2.caption": (
        "Its hash incorporates the previous event's hash",
        "इसका hash पिछले event के hash को शामिल करता है",
        "याचा hash मागील event च्या hash चा समावेश करतो",
        "Iska hash previous event ke hash ko incorporate karta hai",
    ),
    "audit-timeline.steps.3.label": ("Verifiable", "सत्यापन योग्य (Verifiable)", "पडताळणीयोग्य (Verifiable)", "Verifiable"),
    "audit-timeline.steps.3.caption": (
        "Any later tampering breaks the chain and is detectable",
        "बाद में की गई कोई भी छेड़छाड़ chain को तोड़ देती है और पकड़ी जा सकती है",
        "नंतर केलेली कोणतीही छेडछाड chain तोडते आणि ती शोधता येते",
        "Baad mein hui koi bhi tampering chain ko break kar deti hai aur detect ho jaati hai",
    ),
    "audit-timeline.fieldRules.0.name": ("Resource Type", "Resource Type", "Resource Type", "Resource Type"),
    "audit-timeline.fieldRules.0.description": (
        "Filters the feed to one entity (assets, users, roles, …); options are built from whatever events actually loaded",
        "feed को एक entity (assets, users, roles, …) तक filter करता है; options वास्तव में load हुए events के आधार पर बनते हैं",
        "feed ला एका entity (assets, users, roles, …) पर्यंत filter करते; options प्रत्यक्षात load झालेल्या events वरून तयार होतात",
        "Feed ko ek entity (assets, users, roles, …) tak filter karta hai; options wahi hote hain jo events actually load hue hain",
    ),
    "audit-timeline.fieldRules.1.name": ("Action", "Action", "Action", "Action"),
    "audit-timeline.fieldRules.1.description": (
        "The operation performed, humanized from the raw event action string (e.g. asset.updated → Updated)",
        "किया गया operation, raw event action string से human-readable बनाया गया (जैसे asset.updated → Updated)",
        "केलेले operation, raw event action string मधून human-readable बनवलेले (उदा. asset.updated → Updated)",
        "Jo operation perform hua, raw event action string se humanize karke dikhaya jaata hai (jaise asset.updated → Updated)",
    ),
    "audit-timeline.fieldRules.2.name": ("By", "By", "By", "By"),
    "audit-timeline.fieldRules.2.description": (
        "The acting user, resolved by id; shows \"system\" when no user is attached to the event",
        "action करने वाला user, id से resolve किया गया; जब event से कोई user जुड़ा नहीं होता तो \"system\" दिखाया जाता है",
        "action करणारा user, id वरून resolve केलेला; event ला कोणताही user जोडलेला नसेल तेव्हा \"system\" दाखवले जाते",
        "Action karne wala user, id se resolve kiya jaata hai; jab event ke saath koi user attached nahi hota to \"system\" dikhaya jaata hai",
    ),
    "audit-timeline.fieldRules.3.name": ("Seq #", "Seq #", "Seq #", "Seq #"),
    "audit-timeline.fieldRules.3.description": (
        "The event's position in the tamper-evident hash chain — used by the integrity verify check",
        "tamper-evident hash chain में event की position — integrity verify check द्वारा उपयोग की जाती है",
        "tamper-evident hash chain मध्ये event चे स्थान — integrity verify check द्वारे वापरले जाते",
        "Tamper-evident hash chain mein event ki position — integrity verify check isi ko use karta hai",
    ),
    "audit-timeline.tip.title": (
        "Only some resources show a friendly name",
        "केवल कुछ resources ही friendly name दिखाते हैं",
        "फक्त काही resources च friendly name दाखवतात",
        "Sirf kuch resources hi friendly name dikhate hain",
    ),
    "audit-timeline.tip.body": (
        "Resource names are only resolved for assets, roles, tickets, contracts and users — everything else (masters, custody, settings, workflows) falls back to a shortened id; hover it to see the full id in a tooltip.",
        "Resource names केवल assets, roles, tickets, contracts और users के लिए resolve किए जाते हैं — बाकी सब कुछ (masters, custody, settings, workflows) shortened id पर fall back करता है; पूरा id tooltip में देखने के लिए उस पर hover करें।",
        "Resource names फक्त assets, roles, tickets, contracts आणि users साठी resolve केली जातात — बाकी सर्व (masters, custody, settings, workflows) shortened id वर fall back होते; पूर्ण id tooltip मध्ये पाहण्यासाठी त्यावर hover करा.",
        "Resource names sirf assets, roles, tickets, contracts aur users ke liye resolve hote hain — baaki sab kuch (masters, custody, settings, workflows) shortened id par fall back karta hai; poora id tooltip mein dekhne ke liye usse hover karein.",
    ),
}


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_TIMELINE.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_TIMELINE)} audit-timeline keys.")


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