"""One-off seed: registers translation_keys + hi/mr/hinglish translation_values
for the "template-masters" page's PageInfoButton content (Master Data > Template Masters).

Usage: docker compose exec api python seed_translations_pageinfo_template_masters.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)
TEMPLATE_MASTERS = {
    "template-masters.title": (
        "Template Masters",
        "टेम्पलेट मास्टर्स",
        "टेम्पलेट मास्टर्स",
        "Template Masters",
    ),
    "template-masters.subtitle": (
        "How this register works and what each field controls",
        "यह रजिस्टर कैसे काम करता है और हर फ़ील्ड क्या नियंत्रित करती है",
        "हे रजिस्टर कसे कार्य करते आणि प्रत्येक फील्ड काय नियंत्रित करते",
        "Ye register kaise kaam karta hai aur har field kya control karti hai",
    ),
    "template-masters.body.0": (
        "A header/footer (rich text) applied to PDF or Excel exports across the app. Only one template per type — PDF or Excel — is active at a time; activating one deactivates its sibling.",
        "यह एक हेडर/फ़ूटर (रिच टेक्स्ट) है जो ऐप भर में PDF या Excel एक्सपोर्ट पर लागू होता है। प्रत्येक प्रकार — PDF या Excel — के लिए एक समय में केवल एक टेम्पलेट सक्रिय रहता है; किसी एक को सक्रिय करने पर उसका समकक्ष निष्क्रिय हो जाता है।",
        "हे एक हेडर/फूटर (रिच टेक्स्ट) आहे जे संपूर्ण अ‍ॅपमध्ये PDF किंवा Excel एक्सपोर्टवर लागू होते. प्रत्येक प्रकारासाठी — PDF किंवा Excel — एका वेळी फक्त एकच टेम्पलेट सक्रिय असतो; एक सक्रिय केल्यास त्याचा जोडीदार निष्क्रिय होतो.",
        "Ye ek header/footer (rich text) hai jo poore app mein PDF ya Excel exports par apply hota hai. Har type ke liye — PDF ya Excel — ek time par sirf ek hi template active rehta hai; ek ko activate karne se uska sibling deactivate ho jaata hai.",
    ),
    "template-masters.stepsHeading": (
        "How a template goes live",
        "एक टेम्पलेट लाइव कैसे होता है",
        "एखादा टेम्पलेट लाइव्ह कसा होतो",
        "Ek template live kaise hota hai",
    ),
    "template-masters.steps.0.label": (
        "Draft",
        "ड्राफ्ट",
        "ड्राफ्ट",
        "Draft",
    ),
    "template-masters.steps.0.caption": (
        "Just created",
        "अभी बनाया गया",
        "नुकतेच तयार केले",
        "Abhi create hua",
    ),
    "template-masters.steps.1.label": (
        "Edit",
        "संपादित करें",
        "संपादित करा",
        "Edit",
    ),
    "template-masters.steps.1.caption": (
        "Author header/footer",
        "हेडर/फ़ूटर तैयार करें",
        "हेडर/फूटर तयार करा",
        "Header/footer author karein",
    ),
    "template-masters.steps.2.label": (
        "Set Active",
        "सक्रिय करें",
        "सक्रिय करा",
        "Set Active",
    ),
    "template-masters.steps.2.caption": (
        "One per type",
        "प्रति प्रकार एक",
        "प्रति प्रकार एक",
        "Har type ke liye ek",
    ),
    "template-masters.steps.3.label": (
        "Applied",
        "लागू",
        "लागू",
        "Applied",
    ),
    "template-masters.steps.3.caption": (
        "Used on export",
        "एक्सपोर्ट पर उपयोग किया जाता है",
        "एक्सपोर्टवर वापरले जाते",
        "Export par use hota hai",
    ),
    "template-masters.fieldRules.0.name": (
        "Type",
        "प्रकार",
        "प्रकार",
        "Type",
    ),
    "template-masters.fieldRules.0.description": (
        "PDF or Excel — each type has its own separately-active template.",
        "PDF या Excel — प्रत्येक प्रकार का अपना अलग से सक्रिय टेम्पलेट होता है।",
        "PDF किंवा Excel — प्रत्येक प्रकाराचा स्वतःचा वेगळा सक्रिय टेम्पलेट असतो.",
        "PDF ya Excel — har type ka apna separately-active template hota hai.",
    ),
    "template-masters.fieldRules.1.name": (
        "Subject",
        "विषय",
        "विषय",
        "Subject",
    ),
    "template-masters.fieldRules.1.description": (
        "Plain-text title line shown at the top of the export.",
        "एक्सपोर्ट के शीर्ष पर दिखाई देने वाली प्लेन-टेक्स्ट शीर्षक पंक्ति।",
        "एक्सपोर्टच्या वरच्या भागात दिसणारी प्लेन-टेक्स्ट शीर्षक ओळ.",
        "Export ke top par dikhne wali plain-text title line.",
    ),
    "template-masters.fieldRules.2.name": (
        "Header / Footer",
        "हेडर / फ़ूटर",
        "हेडर / फूटर",
        "Header / Footer",
    ),
    "template-masters.fieldRules.2.description": (
        "Rich text — supports placeholders resolved at export time.",
        "रिच टेक्स्ट — एक्सपोर्ट के समय हल किए जाने वाले प्लेसहोल्डर्स का समर्थन करता है।",
        "रिच टेक्स्ट — एक्सपोर्टच्या वेळी सोडवले जाणारे प्लेसहोल्डर्स सपोर्ट करते.",
        "Rich text — export time par resolve hone wale placeholders support karta hai.",
    ),
    "template-masters.tip.title": (
        "Available placeholders",
        "उपलब्ध प्लेसहोल्डर्स",
        "उपलब्ध प्लेसहोल्डर्स",
        "Available placeholders",
    ),
    "template-masters.tip.body": (
        "{{date}}, {{time}}, {{datetime}}, {{user_name}}, {{record_count}} and {{report_name}} are replaced with real values on every export. An unrecognized {{token}} is left as-is so a typo is easy to spot.",
        "{{date}}, {{time}}, {{datetime}}, {{user_name}}, {{record_count}} और {{report_name}} को हर एक्सपोर्ट पर वास्तविक मानों से बदल दिया जाता है। किसी अपरिचित {{token}} को ज्यों का त्यों छोड़ दिया जाता है ताकि टाइपो पहचानना आसान हो।",
        "{{date}}, {{time}}, {{datetime}}, {{user_name}}, {{record_count}} आणि {{report_name}} हे प्रत्येक एक्सपोर्टवर वास्तविक मूल्यांनी बदलले जातात. एखादा अपरिचित {{token}} जसाच्या तसा ठेवला जातो जेणेकरून टायपो सहज ओळखता येईल.",
        "{{date}}, {{time}}, {{datetime}}, {{user_name}}, {{record_count}} aur {{report_name}} har export par real values se replace ho jaate hain. Koi unrecognized {{token}} as-is chhod diya jaata hai taaki typo easily spot ho sake.",
    ),
}


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 TEMPLATE_MASTERS.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(TEMPLATE_MASTERS)} template-masters keys.")


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