"""One-off seed: registers translation_keys English source_text and hi/mr/hinglish
translation_values for the "help" (Help Center) PageInfoButton content.

Usage: docker compose exec api python seed_translations_pageinfo_help.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)
HELP = {
    "help.title": (
        "AAMS Help Center",
        "AAMS हेल्प सेंटर",
        "AAMS हेल्प सेंटर",
        "AAMS Help Center",
    ),
    "help.subtitle": (
        "Guides, workflows and how-tos for every module",
        "हर module के लिए guides, workflows और how-to",
        "प्रत्येक module साठी guides, workflows आणि how-to",
        "Har module ke liye guides, workflows aur how-tos",
    ),
    "help.body.0": (
        "System guidelines, workflows and step-by-step guides for every module.",
        "हर module के लिए system guidelines, workflows और चरण-दर-चरण guides.",
        "प्रत्येक module साठी system guidelines, workflows आणि चरण-दर-चरण guides.",
        "Har module ke liye system guidelines, workflows aur step-by-step guides.",
    ),
    "help.body.1": (
        "Guides are organized into four tabs on the left. Search narrows the list within the tab you're on; picking a guide opens it in the panel on the right with its steps, tips and related screen links.",
        "Guides बाईं ओर चार tabs में व्यवस्थित हैं। Search आपके वर्तमान tab के भीतर सूची को सीमित करता है; कोई guide चुनने पर वह दाईं ओर के panel में उसके steps, tips और related screen links के साथ खुलती है।",
        "Guides डाव्या बाजूला चार tabs मध्ये व्यवस्थित आहेत. Search तुम्ही असलेल्या tab मधील यादी मर्यादित करते; एखादी guide निवडल्यास ती उजव्या बाजूच्या panel मध्ये तिच्या steps, tips आणि related screen links सह उघडते.",
        "Guides left side par chaar tabs mein organize hain. Search aapke current tab ke andar hi list ko narrow karta hai; koi guide select karne par wo right panel mein apne steps, tips aur related screen links ke saath open hoti hai.",
    ),
    "help.stepsHeading": (
        "The four guide tabs",
        "चार guide tabs",
        "चार guide tabs",
        "Chaar guide tabs",
    ),
    "help.steps.0.label": ("Setup", "सेटअप", "सेटअप", "Setup"),
    "help.steps.0.caption": (
        "First-time system setup, in the right order.",
        "सही क्रम में, पहली बार का system setup।",
        "योग्य क्रमाने, पहिल्यांदाचे system setup.",
        "Sahi order mein, pehli baar ka system setup.",
    ),
    "help.steps.1.label": ("System Workflow", "सिस्टम workflow", "सिस्टम workflow", "System Workflow"),
    "help.steps.1.caption": (
        "How modules connect end-to-end.",
        "Modules end-to-end कैसे जुड़ते हैं।",
        "Modules end-to-end कशा प्रकारे जोडल्या जातात.",
        "Modules end-to-end kaise connect hote hain.",
    ),
    "help.steps.2.label": ("How to Use", "उपयोग कैसे करें", "वापर कसा करावा", "Kaise Use Karein"),
    "help.steps.2.caption": (
        "Step-by-step task guides, grouped by module.",
        "Module के अनुसार समूहित, चरण-दर-चरण task guides।",
        "Module नुसार गटबद्ध केलेले, चरण-दर-चरण task guides.",
        "Module ke hisaab se grouped, step-by-step task guides.",
    ),
    "help.steps.3.label": ("App Side (Mobile)", "ऐप साइड (मोबाइल)", "ॲप साइड (मोबाइल)", "App Side (Mobile)"),
    "help.steps.3.caption": (
        "Field tasks on the mobile app.",
        "मोबाइल ऐप पर field tasks।",
        "मोबाइल ॲपवर field tasks.",
        "Mobile app par field tasks.",
    ),
    "help.fieldRules.0.name": ("Search", "सर्च", "सर्च", "Search"),
    "help.fieldRules.0.description": (
        "Filters guide titles/summaries within the currently selected tab only.",
        "केवल वर्तमान में चयनित tab के भीतर guide titles/summaries को फ़िल्टर करता है।",
        "फक्त सध्या निवडलेल्या tab मधील guide titles/summaries फिल्टर करते.",
        "Sirf current selected tab ke andar hi guide titles/summaries ko filter karta hai.",
    ),
    "help.fieldRules.1.name": ("Tab", "टैब", "टॅब", "Tab"),
    "help.fieldRules.1.description": (
        "Switches the guide category — Setup, System Workflow, How-to or App Side.",
        "Guide category बदलता है — Setup, System Workflow, How-to या App Side।",
        "Guide category बदलते — Setup, System Workflow, How-to किंवा App Side.",
        "Guide category switch karta hai — Setup, System Workflow, How-to ya App Side.",
    ),
    "help.fieldRules.2.name": ("Module group", "Module समूह", "Module गट", "Module Group"),
    "help.fieldRules.2.description": (
        "On the How-to tab, guides are grouped under their owning module.",
        "How-to tab पर, guides उनके owning module के अंतर्गत समूहित होती हैं।",
        "How-to tab वर, guides त्यांच्या owning module अंतर्गत गटबद्ध केल्या जातात.",
        "How-to tab par, guides apne owning module ke under grouped hoti hain.",
    ),
    "help.fieldRules.3.name": ("Was this helpful", "क्या यह सहायक था", "हे उपयुक्त होते का", "Was This Helpful"),
    "help.fieldRules.3.description": (
        "Thumbs up/down vote per guide, saved only in this browser (localStorage), not sent to a server.",
        "प्रति guide thumbs up/down vote, केवल इस browser में (localStorage) सेव होता है, किसी server पर नहीं भेजा जाता।",
        "प्रत्येक guide साठी thumbs up/down vote, फक्त या browser मध्ये (localStorage) सेव्ह होते, कोणत्याही server ला पाठवले जात नाही.",
        "Har guide ke liye thumbs up/down vote, sirf isi browser mein (localStorage) save hota hai, kisi server ko nahi bheja jaata.",
    ),
    "help.tip.title": (
        "Export downloads everything, not just what's shown",
        "Export सब कुछ डाउनलोड करता है, सिर्फ जो दिख रहा है वह नहीं",
        "Export सर्व काही डाउनलोड करते, फक्त जे दिसत आहे तेवढेच नाही",
        "Export sab kuch download karta hai, sirf jo dikh raha hai wahi nahi",
    ),
    "help.tip.body": (
        "The Export button always downloads the full guide library as CSV — it ignores your current tab and search filter, so you don't need to clear them first.",
        "Export button हमेशा पूरी guide library को CSV के रूप में डाउनलोड करता है — यह आपके वर्तमान tab और search filter को नज़रअंदाज़ करता है, इसलिए आपको पहले उन्हें साफ़ करने की ज़रूरत नहीं है।",
        "Export button नेहमी संपूर्ण guide library CSV म्हणून डाउनलोड करते — ते तुमच्या सध्याच्या tab आणि search filter कडे दुर्लक्ष करते, त्यामुळे तुम्हाला ते आधी साफ करण्याची गरज नाही.",
        "Export button hamesha poori guide library ko CSV ke roop mein download karta hai — ye aapke current tab aur search filter ko ignore karta hai, isliye pehle unhe clear karne ki zaroorat nahi 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 HELP.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(HELP)} help keys.")


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