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

Usage: docker compose exec api python seed_translations_pageinfo_ai_copilot.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)
AI_COPILOT = {
    "ai-copilot.title": (
        "AI Copilot",
        "एआई कोपायलट",
        "एआय कोपायलट",
        "AI Copilot",
    ),
    "ai-copilot.subtitle": (
        "Ask questions about your assets, warranties, custody, vendors, contracts, insurance, compliance, and reports",
        "अपने assets, warranties, custody, vendors, contracts, insurance, compliance, और reports के बारे में प्रश्न पूछें",
        "तुमच्या assets, warranties, custody, vendors, contracts, insurance, compliance, आणि reports बद्दल प्रश्न विचारा",
        "Apne assets, warranties, custody, vendors, contracts, insurance, compliance, aur reports ke baare mein sawaal poochein",
    ),
    "ai-copilot.body.0": (
        "AI Copilot is a read-only conversational assistant over your tenant's AMS data. It answers questions in plain English by calling the same APIs you have access to — it never creates, edits, or deletes records on your behalf.",
        "AI Copilot आपके tenant के AMS डेटा पर एक read-only conversational assistant है। यह उन्हीं APIs को कॉल करके सामान्य भाषा में प्रश्नों के उत्तर देता है जिन तक आपकी पहुँच है — यह आपकी ओर से कभी भी कोई record नहीं बनाता, संपादित नहीं करता, या हटाता नहीं है।",
        "AI Copilot हे तुमच्या tenant च्या AMS डेटावरील एक read-only conversational assistant आहे. हे तुमच्याकडे प्रवेश असलेल्या त्याच APIs ला कॉल करून साध्या भाषेत प्रश्नांची उत्तरे देते — हे तुमच्या वतीने कधीही कोणताही record तयार करत नाही, संपादित करत नाही, किंवा हटवत नाही.",
        "AI Copilot aapke tenant ke AMS data par ek read-only conversational assistant hai. Ye unhi APIs ko call karke plain language mein sawaalon ke jawaab deta hai jin tak aapki access hai — ye aapki taraf se kabhi bhi koi record create, edit, ya delete nahi karta.",
    ),
    "ai-copilot.body.1": (
        "Every conversation is saved automatically so you can return to it later. Use \"New Chat\" to start a fresh topic without losing earlier history.",
        "हर conversation अपने आप save हो जाती है ताकि आप बाद में इसे दोबारा देख सकें। पुराने history को खोए बिना नए topic पर बात शुरू करने के लिए \"New Chat\" का उपयोग करें।",
        "प्रत्येक conversation आपोआप save होते जेणेकरून तुम्ही नंतर परत त्यावर जाऊ शकाल. जुना history न गमावता नवीन topic वर बोलणे सुरू करण्यासाठी \"New Chat\" वापरा.",
        "Har conversation apne aap save ho jaati hai taaki aap baad mein use dobara dekh sakein. Purani history khoye bina naye topic par baat shuru karne ke liye \"New Chat\" use karein.",
    ),
    "ai-copilot.stepsHeading": (
        "How a conversation works",
        "एक conversation कैसे काम करती है",
        "एक conversation कशी कार्य करते",
        "Ek conversation kaise kaam karti hai",
    ),
    "ai-copilot.steps.0.label": ("Ask", "पूछें", "विचारा", "Ask"),
    "ai-copilot.steps.0.caption": (
        "Type a question and press Enter (Shift+Enter for a new line).",
        "एक प्रश्न टाइप करें और Enter दबाएँ (नई लाइन के लिए Shift+Enter)।",
        "एक प्रश्न टाइप करा आणि Enter दाबा (नवीन ओळीसाठी Shift+Enter).",
        "Ek sawaal type karein aur Enter dabayein (nayi line ke liye Shift+Enter).",
    ),
    "ai-copilot.steps.1.label": ("Streaming reply", "स्ट्रीमिंग रिप्लाई", "स्ट्रीमिंग रिप्लाय", "Streaming reply"),
    "ai-copilot.steps.1.caption": (
        "The answer streams in token-by-token as the model reasons over your data.",
        "जैसे-जैसे मॉडल आपके data पर विश्लेषण करता है, उत्तर token-by-token स्ट्रीम होता है।",
        "मॉडेल तुमच्या data वर विश्लेषण करत असताना उत्तर token-by-token स्ट्रीम होते.",
        "Jaise-jaise model aapke data par reasoning karta hai, answer token-by-token stream hota hai.",
    ),
    "ai-copilot.steps.2.label": ("Saved automatically", "स्वतः सहेजा गया", "आपोआप जतन केले", "Automatically saved"),
    "ai-copilot.steps.2.caption": (
        "The exchange is saved as a conversation and appears in the history list.",
        "यह exchange एक conversation के रूप में save हो जाता है और history list में दिखाई देता है।",
        "हे exchange एक conversation म्हणून save होते आणि history list मध्ये दिसते.",
        "Ye exchange ek conversation ke roop mein save ho jaata hai aur history list mein dikhta hai.",
    ),
    "ai-copilot.steps.3.label": ("Continue or branch", "जारी रखें या नई शाखा बनाएँ", "सुरू ठेवा किंवा नवीन शाखा तयार करा", "Continue ya branch karein"),
    "ai-copilot.steps.3.caption": (
        "Reopen it to keep asking follow-ups, or start a New Chat for a new topic.",
        "Follow-up प्रश्न पूछते रहने के लिए इसे फिर से खोलें, या नए topic के लिए New Chat शुरू करें।",
        "Follow-up प्रश्न विचारत राहण्यासाठी हे पुन्हा उघडा, किंवा नवीन topic साठी New Chat सुरू करा.",
        "Follow-up sawaal poochte rehne ke liye ise dobara kholein, ya naye topic ke liye New Chat shuru karein.",
    ),
    "ai-copilot.fieldRules.0.name": ("Message", "संदेश", "संदेश", "Message"),
    "ai-copilot.fieldRules.0.description": (
        "Send is disabled until you type non-whitespace text, and again while a reply is streaming.",
        "Send तब तक disabled रहता है जब तक आप non-whitespace text टाइप नहीं करते, और फिर जवाब स्ट्रीम होने के दौरान भी disabled रहता है।",
        "जोपर्यंत तुम्ही non-whitespace text टाइप करत नाही तोपर्यंत Send disabled राहते, आणि उत्तर स्ट्रीम होत असताना पुन्हा disabled होते.",
        "Jab tak aap non-whitespace text type nahi karte tab tak Send disabled rehta hai, aur reply stream hone ke dauran bhi dobara disabled ho jaata hai.",
    ),
    "ai-copilot.fieldRules.1.name": ("Conversation title", "Conversation शीर्षक", "Conversation शीर्षक", "Conversation title"),
    "ai-copilot.fieldRules.1.description": (
        "Auto-generated from your first message; shown in the history rail so you can find it again.",
        "आपके पहले संदेश से auto-generate होता है; history rail में दिखाया जाता है ताकि आप इसे दोबारा ढूंढ सकें।",
        "तुमच्या पहिल्या संदेशावरून auto-generate होते; history rail मध्ये दाखवले जाते जेणेकरून तुम्ही ते पुन्हा शोधू शकाल.",
        "Aapke pehle message se auto-generate hota hai; history rail mein dikhaya jaata hai taaki aap use dobara dhoond sakein.",
    ),
    "ai-copilot.fieldRules.2.name": ("Last message preview", "लास्ट मैसेज प्रीव्यू", "लास्ट मेसेज प्रिव्ह्यू", "Last message preview"),
    "ai-copilot.fieldRules.2.description": (
        "Shows a snippet of the most recent user message in the history list, updated after each reply.",
        "History list में सबसे हाल के user संदेश का एक snippet दिखाता है, जो हर जवाब के बाद अपडेट होता है।",
        "History list मध्ये सर्वात अलीकडील user संदेशाचा एक snippet दाखवते, जे प्रत्येक उत्तरानंतर अपडेट होते.",
        "History list mein sabse recent user message ka ek snippet dikhata hai, jo har reply ke baad update hota hai.",
    ),
    "ai-copilot.tip.title": (
        "Deleting is permanent",
        "हटाना स्थायी है",
        "हटवणे कायमस्वरूपी आहे",
        "Delete karna permanent hai",
    ),
    "ai-copilot.tip.body": (
        "The delete (trash) icon on a history entry removes that conversation immediately with no undo — there is no archive or recovery. If Copilot shows \"not enabled for this tenant\", the AI module is switched off for your organization; ask an administrator to enable it rather than retrying.",
        "History entry पर मौजूद delete (trash) icon उस conversation को तुरंत हटा देता है, कोई undo नहीं है — कोई archive या recovery उपलब्ध नहीं है। यदि Copilot \"not enabled for this tenant\" दिखाता है, तो इसका मतलब है कि आपके organization के लिए AI module बंद है; दोबारा कोशिश करने के बजाय किसी administrator से इसे enable करने के लिए कहें।",
        "History entry वरील delete (trash) icon ती conversation लगेच हटवते, कोणतेही undo नाही — कोणतेही archive किंवा recovery उपलब्ध नाही. जर Copilot \"not enabled for this tenant\" असे दाखवत असेल, तर याचा अर्थ तुमच्या organization साठी AI module बंद आहे; पुन्हा प्रयत्न करण्याऐवजी administrator ला ते enable करण्यास सांगा.",
        "History entry par mojood delete (trash) icon us conversation ko turant remove kar deta hai, koi undo nahi hai — koi archive ya recovery available nahi hai. Agar Copilot \"not enabled for this tenant\" dikhata hai, to iska matlab hai ki aapke organization ke liye AI module band hai; dobara try karne ke bajaye kisi administrator se ise enable karne ke liye kahein.",
    ),
}


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 AI_COPILOT.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(AI_COPILOT)} ai-copilot keys.")


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