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

Usage: docker compose exec api python seed_translations_pageinfo_document_repository.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_REPOSITORY = {
    "document-repository.title": (
        "Document Repository Search",
        "डॉक्यूमेंट रिपॉजिटरी सर्च",
        "डॉक्युमेंट रिपॉझिटरी सर्च",
        "Document Repository Search",
    ),
    "document-repository.subtitle": (
        "How the search works and what each result tells you",
        "search कैसे काम करता है और हर result क्या बताता है",
        "search कसा काम करतो आणि प्रत्येक result काय सांगतो",
        "Search kaise kaam karta hai aur har result kya batata hai",
    ),
    "document-repository.body.0": (
        "Full-text search across every document in the register — filename and OCR-extracted content, not just metadata.",
        "रजिस्टर के हर document में full-text search — सिर्फ़ metadata नहीं, बल्कि filename और OCR से निकाली गई content भी शामिल।",
        "रजिस्टरमधील प्रत्येक document मध्ये full-text search — फक्त metadata नाही, तर filename आणि OCR ने काढलेली content देखील समाविष्ट.",
        "Register ke har document mein full-text search hota hai — sirf metadata nahi, balki filename aur OCR se nikali gayi content bhi shaamil hai.",
    ),
    "document-repository.body.1": (
        "Results are scoped to your organisational unit. This page is search-only: uploading, versioning, linking, or deleting a document happens on that document's own asset, under Asset Details → Documents.",
        "Results आपकी organisational unit तक सीमित होते हैं। यह पेज सिर्फ़ search के लिए है: किसी document को upload, version, link या delete करना उस document के अपने asset पर, Asset Details → Documents के अंतर्गत होता है।",
        "Results तुमच्या organisational unit पुरते मर्यादित असतात. हे पान फक्त search साठी आहे: एखादा document upload, version, link किंवा delete करणे त्या document च्या स्वतःच्या asset वर, Asset Details → Documents अंतर्गत होते.",
        "Results aapki organisational unit tak scoped hote hain. Ye page sirf search ke liye hai: kisi document ko upload, version, link ya delete karna us document ke apne asset par, Asset Details → Documents ke andar hota hai.",
    ),
    "document-repository.stepsHeading": (
        "How a search resolves",
        "एक search कैसे resolve होती है",
        "एक search कशी resolve होते",
        "Ek search kaise resolve hoti hai",
    ),
    "document-repository.steps.0.label": ("Enter Query", "Query दर्ज करें", "Query टाका", "Query enter karein"),
    "document-repository.steps.0.caption": (
        "At least 2 characters",
        "कम से कम 2 characters",
        "किमान 2 characters",
        "Kam se kam 2 characters",
    ),
    "document-repository.steps.1.label": ("Search", "Search करें", "Search करा", "Search karein"),
    "document-repository.steps.1.caption": (
        "Ranks by relevance",
        "relevance के अनुसार rank करता है",
        "relevance नुसार rank करते",
        "Relevance ke hisaab se rank karta hai",
    ),
    "document-repository.steps.2.label": (
        "Review Results",
        "Results की समीक्षा करें",
        "Results चा आढावा घ्या",
        "Results review karein",
    ),
    "document-repository.steps.2.caption": (
        "Type, OCR status, snippet",
        "Type, OCR status, snippet",
        "Type, OCR status, snippet",
        "Type, OCR status, snippet",
    ),
    "document-repository.steps.3.label": ("Open Asset", "Asset खोलें", "Asset उघडा", "Asset open karein"),
    "document-repository.steps.3.caption": (
        "Jumps to Documents tab",
        "Documents tab पर ले जाता है",
        "Documents tab वर घेऊन जाते",
        "Documents tab par le jaata hai",
    ),
    "document-repository.fieldRules.0.name": ("Search box", "Search box", "Search box", "Search box"),
    "document-repository.fieldRules.0.description": (
        "Must be at least 2 characters, or the search is blocked with a validation message.",
        "कम से कम 2 characters होने चाहिए, वरना search एक validation message के साथ block हो जाता है।",
        "किमान 2 characters असणे आवश्यक आहे, अन्यथा search एका validation message सह block होतो.",
        "Kam se kam 2 characters hone chahiye, warna search ek validation message ke saath block ho jaata hai.",
    ),
    "document-repository.fieldRules.1.name": (
        "Document type tag",
        "Document type tag",
        "Document type tag",
        "Document type tag",
    ),
    "document-repository.fieldRules.1.description": (
        "Shown only when the document was classified on upload (e.g. invoice, warranty).",
        "यह तभी दिखता है जब document को upload के समय classify किया गया हो (जैसे invoice, warranty)।",
        "हे तेव्हाच दिसते जेव्हा document upload करताना classify केलेला असतो (उदा. invoice, warranty).",
        "Ye tabhi dikhta hai jab document ko upload ke time classify kiya gaya ho (jaise invoice, warranty).",
    ),
    "document-repository.fieldRules.2.name": ("OCR status", "OCR status", "OCR status", "OCR status"),
    "document-repository.fieldRules.2.description": (
        "\"done\" means the file's text is indexed and searchable; other states mean only the filename can match.",
        "\"done\" का मतलब है कि file का text index हो चुका है और searchable है; बाकी states में सिर्फ़ filename ही match कर सकता है।",
        "\"done\" म्हणजे file चा text index झाला आहे आणि searchable आहे; इतर states मध्ये फक्त filename च match होऊ शकते.",
        "\"done\" ka matlab hai ki file ka text index ho chuka hai aur searchable hai; baaki states mein sirf filename hi match kar sakta hai.",
    ),
    "document-repository.fieldRules.3.name": (
        "Relevance rank",
        "Relevance rank",
        "Relevance rank",
        "Relevance rank",
    ),
    "document-repository.fieldRules.3.description": (
        "A text-match score, not recency — a strong keyword match can outrank a newer upload.",
        "यह एक text-match score है, recency नहीं — एक मजबूत keyword match किसी नए upload से भी ऊपर rank कर सकता है।",
        "हा एक text-match score आहे, recency नाही — एक मजबूत keyword match नवीन upload पेक्षाही वर rank होऊ शकतो.",
        "Ye ek text-match score hai, recency nahi — ek strong keyword match kisi naye upload se bhi upar rank kar sakta hai.",
    ),
    "document-repository.tip.title": (
        "OCR still pending won't content-match",
        "OCR अभी pending हो तो content-match नहीं होगा",
        "OCR अजून pending असेल तर content-match होणार नाही",
        "OCR abhi pending ho to content-match nahi hoga",
    ),
    "document-repository.tip.body": (
        "A scanned file whose OCR status isn't \"done\" only surfaces on filename matches — its content isn't searchable yet. If an expected document is missing from results, check its OCR status on the asset's Documents tab before assuming it wasn't uploaded.",
        "जिस scanned file का OCR status \"done\" नहीं है, वह सिर्फ़ filename matches में दिखती है — उसकी content अभी searchable नहीं है। अगर कोई expected document results में नहीं दिख रहा, तो यह मान लेने से पहले कि वह upload नहीं हुआ, asset के Documents tab पर उसका OCR status ज़रूर जाँच लें।",
        "ज्या scanned file चा OCR status \"done\" नाही, ती फक्त filename matches मध्ये दिसते — तिची content अजून searchable नाही. एखादा expected document results मध्ये दिसत नसेल, तर तो upload झाला नाही असे गृहीत धरण्यापूर्वी asset च्या Documents tab वर त्याचा OCR status नक्की तपासा.",
        "Jis scanned file ka OCR status \"done\" nahi hai, wo sirf filename matches mein dikhti hai — uski content abhi searchable nahi hai. Agar koi expected document results mein missing hai, to ye maan lene se pehle ki wo upload nahi hua, asset ke Documents tab par uska OCR status zaroor check karein.",
    ),
}


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_REPOSITORY.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_REPOSITORY)} document-repository keys.")


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