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

Usage: docker compose exec api python seed_translations_pageinfo_document_reports.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_REPORTS = {
    "document-reports.title": (
        "Document Expiry Report",
        "दस्तावेज़ समाप्ति रिपोर्ट",
        "दस्तऐवज मुदतसमाप्ती अहवाल",
        "Document Expiry Report",
    ),
    "document-reports.subtitle": (
        "What's expiring, what's overdue, and how the window filter works",
        "क्या समाप्त हो रहा है, क्या ओवरड्यू है, और विंडो फ़िल्टर कैसे काम करता है",
        "काय संपत आहे, काय ओव्हरड्यू आहे, आणि विंडो फिल्टर कसे कार्य करते",
        "Kya expire ho raha hai, kya overdue hai, aur window filter kaise kaam karta hai",
    ),
    "document-reports.body.0": (
        "Lists asset documents (warranties, licences, certificates) with an expiry date, drawn from the same records shown in the Document Repository. Use it to see what needs renewal action before it lapses.",
        "यह asset documents (warranties, licences, certificates) को उनकी expiry date के साथ सूचीबद्ध करता है, जो Document Repository में दिखाए गए समान records से लिए गए हैं। इसका उपयोग यह देखने के लिए करें कि किसी दस्तावेज़ के lapse होने से पहले किस renewal कार्रवाई की आवश्यकता है।",
        "हा अहवाल asset documents (warranties, licences, certificates) यांना त्यांच्या expiry date सह सूचीबद्ध करतो, जे Document Repository मध्ये दाखवलेल्या त्याच records मधून घेतले आहेत. एखादा दस्तऐवज lapse होण्यापूर्वी कोणती renewal कृती आवश्यक आहे हे पाहण्यासाठी याचा वापर करा.",
        "Ye asset documents (warranties, licences, certificates) ko unki expiry date ke saath list karta hai, jo Document Repository mein dikhaye gaye same records se liye gaye hain. Isse dekhein ki koi document lapse hone se pehle kaunsi renewal action chahiye.",
    ),
    "document-reports.stepsHeading": (
        "How this report works",
        "यह रिपोर्ट कैसे काम करती है",
        "हा अहवाल कसा कार्य करतो",
        "Ye report kaise kaam karta hai",
    ),
    "document-reports.steps.0.label": ("Set Window", "विंडो सेट करें", "विंडो सेट करा", "Window Set Karein"),
    "document-reports.steps.0.caption": (
        "Days Ahead (1–365) sets the forward-looking horizon",
        "Days Ahead (1–365) आगे देखने की समय-सीमा निर्धारित करता है",
        "Days Ahead (1–365) पुढे-पाहणारी कालमर्यादा सेट करते",
        "Days Ahead (1–365) forward-looking horizon set karta hai",
    ),
    "document-reports.steps.1.label": ("Refresh", "रिफ्रेश करें", "रिफ्रेश करा", "Refresh Karein"),
    "document-reports.steps.1.caption": (
        "Re-queries the server for that window",
        "उस विंडो के लिए सर्वर को फिर से क्वेरी करता है",
        "त्या विंडोसाठी सर्व्हरला पुन्हा क्वेरी करते",
        "Us window ke liye server ko phir se query karta hai",
    ),
    "document-reports.steps.2.label": ("Filter", "फ़िल्टर करें", "फिल्टर करा", "Filter Karein"),
    "document-reports.steps.2.caption": (
        "Narrow by Classification, client-side",
        "Classification के अनुसार, client-side पर सीमित करें",
        "Classification नुसार, client-side वर मर्यादित करा",
        "Classification ke hisaab se, client-side par narrow karein",
    ),
    "document-reports.steps.3.label": ("Review", "समीक्षा करें", "पुनरावलोकन करा", "Review Karein"),
    "document-reports.steps.3.caption": (
        "Overdue (red) vs Expiring (amber) in the table",
        "टेबल में Overdue (लाल) बनाम Expiring (एम्बर)",
        "टेबलमध्ये Overdue (लाल) विरुद्ध Expiring (अंबर)",
        "Table mein Overdue (red) vs Expiring (amber)",
    ),
    "document-reports.fieldRules.0.name": ("Days Ahead", "Days Ahead", "Days Ahead", "Days Ahead"),
    "document-reports.fieldRules.0.description": (
        "Server-side window, 1–365 (default 30). Does not hide already-overdue documents — see tip.",
        "Server-side विंडो, 1–365 (डिफ़ॉल्ट 30). पहले से overdue दस्तावेज़ों को छुपाता नहीं है — टिप देखें।",
        "Server-side विंडो, 1–365 (डीफॉल्ट 30). आधीच overdue असलेले दस्तऐवज लपवत नाही — टिप पहा.",
        "Server-side window, 1–365 (default 30). Already-overdue documents ko hide nahi karta — tip dekhein.",
    ),
    "document-reports.fieldRules.1.name": ("Classification", "Classification", "Classification", "Classification"),
    "document-reports.fieldRules.1.description": (
        "Client-side filter built only from classifications present in the current result set.",
        "Client-side फ़िल्टर जो केवल वर्तमान result set में मौजूद classifications से बनाया जाता है।",
        "Client-side फिल्टर जो फक्त सध्याच्या result set मध्ये असलेल्या classifications मधून तयार केला जातो.",
        "Client-side filter jo sirf current result set mein present classifications se banta hai.",
    ),
    "document-reports.fieldRules.2.name": ("Days", "Days", "Days", "Days"),
    "document-reports.fieldRules.2.description": (
        "Days until expiry from today; negative means already expired.",
        "आज से expiry तक के दिन; ऋणात्मक (negative) का मतलब है कि यह पहले ही समाप्त हो चुका है।",
        "आजपासून expiry पर्यंतचे दिवस; negative म्हणजे आधीच मुदत संपली आहे.",
        "Aaj se expiry tak ke days; negative ka matlab hai already expired ho chuka hai.",
    ),
    "document-reports.fieldRules.3.name": ("Status", "Status", "Status", "Status"),
    "document-reports.fieldRules.3.description": (
        "Overdue/Expiring badge, derived purely from the Days value.",
        "Overdue/Expiring बैज, जो पूरी तरह Days मान से निकाला जाता है।",
        "Overdue/Expiring बॅज, जो पूर्णपणे Days मूल्यावरून काढला जातो.",
        "Overdue/Expiring badge, jo purely Days value se derive hota hai.",
    ),
    "document-reports.tip.title": (
        "Overdue documents always show",
        "Overdue दस्तावेज़ हमेशा दिखते हैं",
        "Overdue दस्तऐवज नेहमी दिसतात",
        "Overdue documents hamesha dikhte hain",
    ),
    "document-reports.tip.body": (
        "Days Ahead only bounds the forward-looking edge of the query — the backend has no lower bound, so documents that already expired appear regardless of window size. Shrinking the window to 1 day won't hide a badly overdue certificate.",
        "Days Ahead केवल क्वेरी के आगे देखने वाले किनारे को सीमित करता है — backend की कोई निचली सीमा नहीं है, इसलिए पहले से समाप्त हो चुके दस्तावेज़ विंडो के आकार की परवाह किए बिना दिखाई देते हैं। विंडो को 1 दिन तक छोटा करने से भी कोई बुरी तरह overdue certificate नहीं छिपेगा।",
        "Days Ahead फक्त क्वेरीच्या पुढे-पाहणाऱ्या टोकाला मर्यादित करते — backend ला खालची मर्यादा नाही, त्यामुळे आधीच मुदत संपलेले दस्तऐवज विंडोच्या आकाराकडे दुर्लक्ष करून दिसतात. विंडो 1 दिवसापर्यंत लहान केल्यानेही एखादे खूप overdue certificate लपणार नाही.",
        "Days Ahead sirf query ke forward-looking edge ko bound karta hai — backend ki koi lower bound nahi hai, isliye already expired documents window size ki parwah kiye bina dikhte hain. Window ko 1 din tak chhota karne se bhi badly overdue certificate hide nahi hoga.",
    ),
}


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_REPORTS.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_REPORTS)} document-reports keys.")


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