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

Usage: docker compose exec api python seed_translations_pageinfo_settings.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)
SETTINGS = {
    "settings.title": (
        "Settings",
        "सेटिंग्स",
        "सेटिंग्ज",
        "Settings",
    ),
    "settings.subtitle": (
        "Tenant-wide branding, policy documents, and map defaults",
        "संपूर्ण tenant के लिए branding, policy दस्तावेज़ और map defaults",
        "संपूर्ण tenant साठी branding, policy कागदपत्रे आणि map defaults",
        "Poore tenant ke liye branding, policy documents, aur map defaults",
    ),
    "settings.body.0": (
        "Configure appearance, legal policy documents, and Geo Workspace map defaults for this tenant, organized into three tabs. Changes apply immediately for every user in the tenant, not just you.",
        "इस tenant के लिए appearance, legal policy दस्तावेज़, और Geo Workspace map defaults को कॉन्फ़िगर करें, जो तीन tabs में व्यवस्थित हैं। बदलाव तुरंत tenant के हर user के लिए लागू होते हैं, सिर्फ़ आपके लिए नहीं।",
        "या tenant साठी appearance, legal policy कागदपत्रे आणि Geo Workspace map defaults कॉन्फिगर करा, जे तीन tabs मध्ये व्यवस्थित आहेत. बदल tenant मधील प्रत्येक user साठी लगेच लागू होतात, फक्त तुमच्यासाठी नाही.",
        "Is tenant ke liye appearance, legal policy documents, aur Geo Workspace map defaults ko configure karein, jo teen tabs mein organize hain. Changes turant tenant ke har user ke liye apply hote hain, sirf aapke liye nahi.",
    ),
    "settings.body.1": (
        "Fields are read-only unless your role has the settings:update permission — Application shows a view-only notice, Policy and Map simply disable their inputs.",
        "Fields तब तक read-only रहती हैं जब तक आपके role में settings:update permission न हो — Application एक view-only notice दिखाता है, जबकि Policy और Map बस अपने inputs को disable कर देते हैं।",
        "जोपर्यंत तुमच्या role कडे settings:update permission नाही, तोपर्यंत fields read-only राहतात — Application एक view-only notice दाखवते, तर Policy आणि Map फक्त त्यांचे inputs disable करतात.",
        "Fields tab tak read-only rehti hain jab tak aapke role mein settings:update permission na ho — Application ek view-only notice dikhata hai, jabki Policy aur Map bas apne inputs disable kar dete hain.",
    ),
    "settings.stepsHeading": (
        "Settings Tabs",
        "सेटिंग्स टैब्स",
        "सेटिंग्ज टॅब्स",
        "Settings Tabs",
    ),
    "settings.steps.0.label": ("Application", "एप्लिकेशन", "अॅप्लिकेशन", "Application"),
    "settings.steps.0.caption": (
        "Logo, favicon, theme colors, and app/login titles.",
        "Logo, favicon, theme colors, और app/login titles।",
        "Logo, favicon, theme colors आणि app/login titles.",
        "Logo, favicon, theme colors, aur app/login titles.",
    ),
    "settings.steps.1.label": ("Policy", "पॉलिसी", "पॉलिसी", "Policy"),
    "settings.steps.1.caption": (
        "Privacy and Terms of Workspace content shown in the footer.",
        "Footer में दिखाई देने वाला Privacy और Terms of Workspace content।",
        "Footer मध्ये दिसणारा Privacy आणि Terms of Workspace content.",
        "Footer mein dikhne wala Privacy aur Terms of Workspace content.",
    ),
    "settings.steps.2.label": ("Map Settings", "मैप सेटिंग्स", "मॅप सेटिंग्ज", "Map Settings"),
    "settings.steps.2.caption": (
        "Default provider, center point, zoom, and API key for Geo Workspace.",
        "Geo Workspace के लिए default provider, center point, zoom, और API key।",
        "Geo Workspace साठी default provider, center point, zoom आणि API key.",
        "Geo Workspace ke liye default provider, center point, zoom, aur API key.",
    ),
    "settings.fieldRules.0.name": ("Logo / Favicon", "लोगो / फ़ेविकॉन", "लोगो / फेव्हिकॉन", "Logo / Favicon"),
    "settings.fieldRules.0.description": (
        "PNG/JPG or PNG/ICO upload shown on the login page and browser tab; \"Reset to default\" clears it.",
        "Login page और browser tab पर दिखने वाला PNG/JPG या PNG/ICO upload; \"Reset to default\" इसे clear कर देता है।",
        "Login page आणि browser tab वर दिसणारे PNG/JPG किंवा PNG/ICO upload; \"Reset to default\" ते clear करते.",
        "Login page aur browser tab par dikhne wala PNG/JPG ya PNG/ICO upload; \"Reset to default\" ise clear kar deta hai.",
    ),
    "settings.fieldRules.1.name": (
        "Primary / Secondary / Button Color",
        "प्राइमरी / सेकेंडरी / बटन कलर",
        "प्रायमरी / सेकंडरी / बटण कलर",
        "Primary / Secondary / Button Color",
    ),
    "settings.fieldRules.1.description": (
        "Drives the tenant's light-mode theme; dark mode uses a fixed palette and ignores these.",
        "यह tenant की light-mode theme तय करता है; dark mode एक fixed palette उपयोग करता है और इन्हें नज़रअंदाज़ करता है।",
        "हे tenant च्या light-mode theme ला चालना देते; dark mode एक fixed palette वापरते आणि यांकडे दुर्लक्ष करते.",
        "Ye tenant ki light-mode theme decide karta hai; dark mode ek fixed palette use karta hai aur inhe ignore karta hai.",
    ),
    "settings.fieldRules.2.name": ("Map Provider", "मैप प्रोवाइडर", "मॅप प्रोव्हायडर", "Map Provider"),
    "settings.fieldRules.2.description": (
        "Leaflet (OpenStreetMap) needs no key; Google Maps requires an API key to render.",
        "Leaflet (OpenStreetMap) को किसी key की ज़रूरत नहीं होती; Google Maps को render करने के लिए API key चाहिए।",
        "Leaflet (OpenStreetMap) साठी कोणतीही key लागत नाही; Google Maps ला render करण्यासाठी API key आवश्यक आहे.",
        "Leaflet (OpenStreetMap) ko koi key nahi chahiye; Google Maps ko render karne ke liye API key chahiye.",
    ),
    "settings.fieldRules.3.name": ("Map API Key", "मैप API की", "मॅप API की", "Map API Key"),
    "settings.fieldRules.3.description": (
        "Used only when Provider is Google Maps; leave blank for Leaflet.",
        "इसका उपयोग तभी होता है जब Provider Google Maps हो; Leaflet के लिए इसे खाली छोड़ दें।",
        "Provider Google Maps असेल तेव्हाच याचा वापर होतो; Leaflet साठी हे रिकामे ठेवा.",
        "Iska use tabhi hota hai jab Provider Google Maps ho; Leaflet ke liye ise blank chhod dein.",
    ),
    "settings.fieldRules.4.name": (
        "Policy Title / Content",
        "पॉलिसी शीर्षक / कंटेंट",
        "पॉलिसी शीर्षक / कंटेंट",
        "Policy Title / Content",
    ),
    "settings.fieldRules.4.description": (
        "Rich-text (Quill) body for the Privacy and Terms of Workspace documents, saved per document.",
        "Privacy और Terms of Workspace दस्तावेज़ों के लिए Rich-text (Quill) body, जो प्रत्येक दस्तावेज़ के अनुसार save होती है।",
        "Privacy आणि Terms of Workspace कागदपत्रांसाठी Rich-text (Quill) body, जी प्रत्येक कागदपत्रानुसार save होते.",
        "Privacy aur Terms of Workspace documents ke liye Rich-text (Quill) body, jo har document ke hisaab se save hoti hai.",
    ),
    "settings.tip.title": (
        "Google Maps key isn't validated on save",
        "सेव करते समय Google Maps key वैलिडेट नहीं होती",
        "सेव्ह करताना Google Maps key व्हॅलिडेट होत नाही",
        "Save karte waqt Google Maps key validate nahi hoti",
    ),
    "settings.tip.body": (
        "Switching Map Provider to Google Maps and saving without an API Key succeeds silently — nothing blocks it. The Geo Workspace map will then fail to render until you come back and add a valid key.",
        "Map Provider को Google Maps में बदलकर बिना API Key के save करना बिना किसी रोक-टोक के सफल हो जाता है — कुछ भी इसे नहीं रोकता। इसके बाद Geo Workspace map तब तक render नहीं होगा जब तक आप वापस आकर एक valid key नहीं जोड़ते।",
        "Map Provider Google Maps मध्ये बदलून API Key शिवाय save करणे कोणत्याही अडथळ्याशिवाय यशस्वी होते — काहीही ते थांबवत नाही. त्यानंतर तुम्ही परत येऊन valid key जोडेपर्यंत Geo Workspace map render होणार नाही.",
        "Map Provider ko Google Maps mein switch karke bina API Key ke save karna chup-chaap succeed ho jaata hai — kuch bhi ise block nahi karta. Uske baad Geo Workspace map tab tak render nahi hoga jab tak aap wapas aakar ek valid key add nahi karte.",
    ),
}


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 SETTINGS.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(SETTINGS)} settings keys.")


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