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

Usage: docker compose exec api python seed_translations_pageinfo_document_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)
DOCUMENT_MASTERS = {
    "document-masters.title": (
        "Document Masters",
        "डॉक्यूमेंट मास्टर",
        "डॉक्युमेंट मास्टर",
        "Document Masters",
    ),
    "document-masters.subtitle": (
        "How document type records are governed and used",
        "डॉक्यूमेंट टाइप रिकॉर्ड्स कैसे नियंत्रित और उपयोग किए जाते हैं",
        "डॉक्युमेंट टाइप रेकॉर्ड्स कशा प्रकारे नियंत्रित आणि वापरले जातात",
        "Document type records kaise govern aur use hote hain",
    ),
    "document-masters.body.0": (
        "Configure legal compliance documents, guarantees, insurance, and retention covenants.",
        "कानूनी अनुपालन (legal compliance) दस्तावेज़, गारंटी, बीमा और रिटेंशन कॉवेनेंट्स को कॉन्फ़िगर करें।",
        "कायदेशीर अनुपालन (legal compliance) कागदपत्रे, गॅरंटी, विमा आणि रिटेंशन कॉव्हेनंट्स कॉन्फिगर करा.",
        "Legal compliance documents, guarantees, insurance, aur retention covenants configure karein.",
    ),
    "document-masters.stepsHeading": (
        "Document type lifecycle",
        "डॉक्यूमेंट टाइप लाइफ़साइकिल",
        "डॉक्युमेंट टाइप लाइफसायकल",
        "Document type ka lifecycle",
    ),
    "document-masters.steps.0.label": ("Draft", "ड्राफ़्ट", "ड्राफ्ट", "Draft"),
    "document-masters.steps.0.caption": (
        "Saved, pending approval",
        "सेव किया गया, अनुमोदन (approval) लंबित",
        "सेव्ह केले, मंजुरी (approval) प्रलंबित",
        "Saved ho gaya, approval pending hai",
    ),
    "document-masters.steps.1.label": ("Active", "सक्रिय", "सक्रिय", "Active"),
    "document-masters.steps.1.caption": (
        "Approved, selectable elsewhere",
        "अनुमोदित, कहीं और चयन योग्य",
        "मंजूर, इतरत्र निवडण्यायोग्य",
        "Approved ho gaya, kahin aur select kiya ja sakta hai",
    ),
    "document-masters.steps.2.label": ("Archived", "आर्काइव्ड", "आर्काइव्ह्ड", "Archived"),
    "document-masters.steps.2.caption": (
        "Deactivated, hidden from pickers",
        "निष्क्रिय किया गया, पिकर्स से छिपा हुआ",
        "निष्क्रिय केले, पिकर्समधून लपवलेले",
        "Deactivate ho gaya, pickers se hide hai",
    ),
    "document-masters.fieldRules.0.name": ("Document code", "डॉक्यूमेंट कोड", "डॉक्युमेंट कोड", "Document code"),
    "document-masters.fieldRules.0.description": (
        "Unique identifier. Locked and cannot be changed once the record is created.",
        "अद्वितीय पहचानकर्ता। रिकॉर्ड बनने के बाद यह लॉक हो जाता है और बदला नहीं जा सकता।",
        "अद्वितीय ओळखकर्ता. रेकॉर्ड तयार झाल्यानंतर हे लॉक होते आणि बदलता येत नाही.",
        "Unique identifier hai. Record create hone ke baad ye lock ho jaata hai aur change nahi kiya ja sakta.",
    ),
    "document-masters.fieldRules.1.name": ("Document name", "डॉक्यूमेंट नाम", "डॉक्युमेंट नाव", "Document name"),
    "document-masters.fieldRules.1.description": (
        "Display name shown wherever this document type can be selected.",
        "डिस्प्ले नाम, जो भी जगह यह डॉक्यूमेंट टाइप चुना जा सकता है वहाँ दिखाया जाता है।",
        "डिस्प्ले नाव, जिथे कुठे हा डॉक्युमेंट टाइप निवडता येतो तिथे दाखवले जाते.",
        "Display name hai, jahan bhi ye document type select kiya ja sakta hai wahan dikhta hai.",
    ),
    "document-masters.fieldRules.2.name": ("Description", "विवरण", "वर्णन", "Description"),
    "document-masters.fieldRules.2.description": (
        "Free-text notes on what the document type covers.",
        "यह डॉक्यूमेंट टाइप क्या कवर करता है, इस पर फ्री-टेक्स्ट नोट्स।",
        "हा डॉक्युमेंट टाइप काय कव्हर करतो, याबाबत फ्री-टेक्स्ट नोट्स.",
        "Ye document type kya cover karta hai, uske baare mein free-text notes.",
    ),
    "document-masters.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "document-masters.fieldRules.3.description": (
        "Draft while awaiting approval, Active once approved, Archived after deactivation.",
        "अनुमोदन की प्रतीक्षा में Draft, अनुमोदित होने पर Active, निष्क्रिय होने के बाद Archived।",
        "मंजुरीच्या प्रतीक्षेत Draft, मंजूर झाल्यावर Active, निष्क्रिय झाल्यानंतर Archived.",
        "Approval ka wait karte waqt Draft, approve hone par Active, deactivate hone ke baad Archived.",
    ),
    "document-masters.tip.title": (
        "Code can't be edited later",
        "कोड को बाद में एडिट नहीं किया जा सकता",
        "कोड नंतर एडिट करता येत नाही",
        "Code baad mein edit nahi kiya ja sakta",
    ),
    "document-masters.tip.body": (
        "The Document Code field is disabled on the edit form — the backend never updates it after creation. Got the code wrong? Create a new record with the right code and archive the old one, rather than trying to fix it in place.",
        "Document Code फ़ील्ड edit फ़ॉर्म पर disabled रहती है — बनने के बाद backend इसे कभी अपडेट नहीं करता। कोड गलत हो गया? सही कोड के साथ एक नया रिकॉर्ड बनाएं और पुराने को आर्काइव कर दें, बजाय इसके कि उसे वहीं ठीक करने की कोशिश करें।",
        "Document Code फील्ड edit फॉर्मवर disabled असते — तयार झाल्यानंतर backend ते कधीच अपडेट करत नाही. कोड चुकीचा गेला? योग्य कोडसह नवीन रेकॉर्ड तयार करा आणि जुने आर्काइव्ह करा, ते जागच्या जागी दुरुस्त करण्याचा प्रयत्न करण्याऐवजी.",
        "Document Code field edit form par disabled rehti hai — create hone ke baad backend ise kabhi update nahi karta. Code galat ho gaya? Sahi code ke saath ek naya record banayein aur purane ko archive kar dein, usse wahin fix karne ki koshish karne ke bajaye.",
    ),
}


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 DOCUMENT_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(DOCUMENT_MASTERS)} document-masters keys.")


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