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

Usage: docker compose exec api python seed_translations_pageinfo_executive_history.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)
EXECUTIVE_HISTORY = {
    "executive-history.title": (
        "Executive History",
        "एग्जीक्यूटिव हिस्ट्री",
        "एग्जीक्यूटिव्ह हिस्ट्री",
        "Executive History",
    ),
    "executive-history.subtitle": (
        "How this trail works and what each column means",
        "यह ट्रेल कैसे काम करता है और प्रत्येक कॉलम का क्या अर्थ है",
        "हे ट्रेल कसे कार्य करते आणि प्रत्येक कॉलमचा अर्थ काय आहे",
        "Ye trail kaise kaam karta hai aur har column ka kya matlab hai",
    ),
    "executive-history.body.0": (
        "Real system audit trail — every mutating API call, hash-chained and tamper-evident.",
        "वास्तविक सिस्टम ऑडिट ट्रेल — हर mutating API call, hash-chained और tamper-evident।",
        "प्रत्यक्ष सिस्टम ऑडिट ट्रेल — प्रत्येक mutating API call, hash-chained आणि tamper-evident.",
        "Real system audit trail — har mutating API call, hash-chained aur tamper-evident hoti hai.",
    ),
    "executive-history.body.1": (
        "Nothing here is editable. Click the eye icon on any row to see the full record, including its hash and IP address.",
        "यहाँ कुछ भी संपादन योग्य (editable) नहीं है। पूरा रिकॉर्ड देखने के लिए, जिसमें उसका hash और IP address भी शामिल है, किसी भी row पर eye आइकन पर क्लिक करें।",
        "येथे काहीही editable नाही. संपूर्ण रेकॉर्ड पाहण्यासाठी, ज्यात त्याचा hash आणि IP address समाविष्ट आहे, कोणत्याही row वरील eye आयकॉनवर क्लिक करा.",
        "Yahan kuch bhi editable nahi hai. Kisi bhi row par eye icon par click karke poora record dekh sakte hain, jisme uska hash aur IP address bhi shamil hai.",
    ),
    "executive-history.stepsHeading": (
        "How an event gets recorded",
        "कोई event कैसे रिकॉर्ड होता है",
        "एखादा event कसा रेकॉर्ड होतो",
        "Ek event kaise record hota hai",
    ),
    "executive-history.steps.0.label": ("Action Occurs", "Action होता है", "Action घडते", "Action hota hai"),
    "executive-history.steps.0.caption": (
        "A mutating API call fires",
        "एक mutating API call फायर होती है",
        "एक mutating API call फायर होते",
        "Ek mutating API call fire hoti hai",
    ),
    "executive-history.steps.1.label": ("Event Hashed", "Event Hash किया जाता है", "Event Hash केले जाते", "Event Hash hota hai"),
    "executive-history.steps.1.caption": (
        "Chained to the prior event's hash",
        "पिछले event के hash से जोड़ा (chain) जाता है",
        "मागील event च्या hash शी chain केले जाते",
        "Pichhle event ke hash se chain kiya jaata hai",
    ),
    "executive-history.steps.2.label": ("Sequenced", "क्रमबद्ध (Sequenced) किया जाता है", "क्रमबद्ध (Sequenced) केले जाते", "Sequence diya jaata hai"),
    "executive-history.steps.2.caption": (
        "Given a permanent, gap-free number",
        "एक स्थायी, gap-free नंबर दिया जाता है",
        "एक कायमस्वरूपी, gap-free नंबर दिला जातो",
        "Ek permanent, gap-free number diya jaata hai",
    ),
    "executive-history.steps.3.label": ("Filter & Inspect", "Filter व Inspect करें", "Filter व Inspect करा", "Filter & Inspect karein"),
    "executive-history.steps.3.caption": (
        "Narrow by resource, open full detail",
        "resource के आधार पर संकीर्ण (narrow) करें, पूरा विवरण खोलें",
        "resource नुसार संकुचित (narrow) करा, संपूर्ण तपशील उघडा",
        "Resource ke hisaab se narrow karein, poora detail open karein",
    ),
    "executive-history.fieldRules.0.name": ("Sequence", "Sequence", "Sequence", "Sequence"),
    "executive-history.fieldRules.0.description": (
        "Strictly increasing sequence_num — a gap means an event is missing from the chain.",
        "सख्ती से बढ़ता हुआ sequence_num — कोई gap यह दर्शाता है कि chain से कोई event गायब है।",
        "काटेकोरपणे वाढणारा sequence_num — कोणताही gap म्हणजे chain मधून एखादा event गहाळ आहे.",
        "Strictly increasing sequence_num hota hai — koi gap ka matlab hai ki chain se ek event missing hai.",
    ),
    "executive-history.fieldRules.1.name": ("Action", "Action", "Action", "Action"),
    "executive-history.fieldRules.1.description": (
        "The operation performed, taken directly from the API call.",
        "किया गया operation, सीधे API call से लिया गया।",
        "केलेले operation, थेट API call वरून घेतलेले.",
        "Jo operation perform hua, wo directly API call se liya gaya hai.",
    ),
    "executive-history.fieldRules.2.name": ("Performed By", "Performed By", "Performed By", "Performed By"),
    "executive-history.fieldRules.2.description": (
        'Resolved from the actor\'s user id; shows "System" when no user is attached (background job).',
        'actor की user id से resolve किया जाता है; जब कोई user जुड़ा न हो (background job) तो "System" दिखाया जाता है।',
        'actor च्या user id वरून resolve केले जाते; जेव्हा कोणताही user जोडलेला नसतो (background job) तेव्हा "System" दाखवले जाते.',
        'Actor ki user id se resolve hota hai; jab koi user attached na ho (background job) to "System" dikhaya jaata hai.',
    ),
    "executive-history.fieldRules.3.name": ("Resource", "Resource", "Resource", "Resource"),
    "executive-history.fieldRules.3.description": (
        "The resource_type badge — also drives the Resource Type filter above the table.",
        "resource_type badge — यह table के ऊपर मौजूद Resource Type filter को भी नियंत्रित करता है।",
        "resource_type badge — हे table वरील Resource Type filter देखील चालवते.",
        "Resource_type badge hai — ye table ke upar wale Resource Type filter ko bhi drive karta hai.",
    ),
    "executive-history.fieldRules.4.name": ("Status", "Status", "Status", "Status"),
    "executive-history.fieldRules.4.description": (
        "Derived from the HTTP status_code (200-399 = SUCCESS), not a stored flag.",
        "HTTP status_code (200-399 = SUCCESS) से derive किया जाता है, यह कोई stored flag नहीं है।",
        "HTTP status_code (200-399 = SUCCESS) वरून derive केले जाते, हे कोणतेही stored flag नाही.",
        "HTTP status_code (200-399 = SUCCESS) se derive hota hai, koi stored flag nahi hai.",
    ),
    "executive-history.tip.title": (
        "Timeline shows the loaded page, not full history",
        "Timeline सिर्फ loaded page दिखाता है, पूरी history नहीं",
        "Timeline फक्त loaded page दाखवते, संपूर्ण history नाही",
        "Timeline sirf loaded page dikhata hai, poori history nahi",
    ),
    "executive-history.tip.body": (
        "Timeline View renders from the same page of rows as Table View — it does not re-fetch the whole trail. Switch to Table View and increase the page size first if you need a wider window before flipping to Timeline.",
        "Timeline View, Table View जैसी ही rows के page से render होता है — यह पूरी trail को दोबारा fetch नहीं करता। Timeline पर जाने से पहले, यदि आपको ज़्यादा wide window चाहिए तो पहले Table View पर स्विच करें और page size बढ़ाएँ।",
        "Timeline View, Table View प्रमाणेच rows च्या त्याच page वरून render होते — ते संपूर्ण trail पुन्हा fetch करत नाही. Timeline वर जाण्यापूर्वी, जर तुम्हाला जास्त wide window हवी असेल तर आधी Table View वर स्विच करा आणि page size वाढवा.",
        "Timeline View, Table View jaise hi rows ke same page se render hota hai — ye poori trail ko dobara fetch nahi karta. Timeline par jaane se pehle, agar aapko wider window chahiye to pehle Table View par switch karein aur page size badhaein.",
    ),
}


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 EXECUTIVE_HISTORY.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(EXECUTIVE_HISTORY)} executive-history keys.")


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