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

Usage: docker compose exec api python seed_translations_pageinfo_service_evidence.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)
SERVICE_EVIDENCE = {
    "service-evidence.title": (
        "Service Evidence Repository",
        "सर्विस एविडेंस रिपॉज़िटरी",
        "सर्व्हिस एव्हिडन्स रिपॉझिटरी",
        "Service Evidence Repository",
    ),
    "service-evidence.subtitle": (
        "Proof of work, filed against the job",
        "काम का प्रमाण, जॉब के विरुद्ध दर्ज",
        "कामाचा पुरावा, जॉबविरुद्ध नोंदवलेला",
        "Kaam ka proof, job ke against file kiya gaya",
    ),
    "service-evidence.body.0": (
        "Every photo, video, or document a technician attaches to a work order lands here, filed against that work order's asset. Pick a work order above to see (or add to) the evidence already on file for it.",
        "टेक्नीशियन द्वारा किसी work order से attach की गई हर photo, video, या document यहाँ आती है, उस work order के asset के विरुद्ध दर्ज होकर। ऊपर कोई work order चुनें ताकि उसके लिए पहले से मौजूद evidence देख सकें (या उसमें जोड़ सकें)।",
        "टेक्निशियनने एखाद्या work order ला attach केलेली प्रत्येक photo, video किंवा document इथे येते, त्या work order च्या asset विरुद्ध नोंदवली जाऊन. वर एखादी work order निवडा जेणेकरून तिच्यासाठी आधीच असलेली evidence पाहता येईल (किंवा त्यात भर घालता येईल).",
        "Technician jo bhi photo, video, ya document kisi work order mein attach karta hai wo yahan aati hai, us work order ke asset ke against file hoke. Upar koi work order select karein taaki uske liye already-file evidence dekh sakein (ya usmein add kar sakein).",
    ),
    "service-evidence.body.1": (
        "Nothing new is stored for this — it's the same asset-document system used elsewhere in AMS, with each file simply tagged as service evidence so it doesn't mix with other document types.",
        "इसके लिए कुछ भी नया store नहीं होता — यह वही asset-document system है जो AMS में बाकी जगह इस्तेमाल होता है, बस हर file को service evidence के रूप में टैग किया जाता है ताकि यह बाकी document types के साथ न मिले।",
        "यासाठी काहीही नवीन store केले जात नाही — हीच asset-document system आहे जी AMS मध्ये इतरत्र वापरली जाते, फक्त प्रत्येक file ला service evidence म्हणून टॅग केले जाते जेणेकरून ती इतर document types सोबत मिसळणार नाही.",
        "Iske liye kuch bhi naya store nahi hota — ye wahi asset-document system hai jo AMS mein baaki jagah use hoti hai, bas har file ko service evidence ke roop mein tag kiya jaata hai taaki ye baaki document types ke saath mix na ho.",
    ),
    "service-evidence.stepsHeading": (
        "Evidence lifecycle",
        "एविडेंस लाइफ़साइकल",
        "एव्हिडन्स लाइफसायकल",
        "Evidence lifecycle",
    ),
    "service-evidence.steps.0.label": (
        "Select Work Order", "Work Order चुनें", "Work Order निवडा", "Work Order Select Karein",
    ),
    "service-evidence.steps.0.caption": (
        "Choose the job whose asset evidence you want to view or add to.",
        "वह job चुनें जिसके asset evidence को आप देखना या जिसमें जोड़ना चाहते हैं।",
        "ती job निवडा ज्याची asset evidence तुम्हाला पाहायची किंवा त्यात भर घालायची आहे.",
        "Wo job choose karein jiski asset evidence aap dekhna ya usmein add karna chahte hain.",
    ),
    "service-evidence.steps.1.label": (
        "Upload Evidence", "Evidence अपलोड करें", "Evidence अपलोड करा", "Evidence Upload Karein",
    ),
    "service-evidence.steps.1.caption": (
        "Attach a photo, video, or document as proof the work was done.",
        "काम पूरा होने के प्रमाण के रूप में photo, video, या document attach करें।",
        "काम पूर्ण झाल्याचा पुरावा म्हणून photo, video किंवा document attach करा.",
        "Kaam complete hone ke proof ke roop mein photo, video, ya document attach karein.",
    ),
    "service-evidence.steps.2.label": (
        "Security Scan", "सिक्योरिटी स्कैन", "सिक्युरिटी स्कॅन", "Security Scan",
    ),
    "service-evidence.steps.2.caption": (
        "The file is scanned before it can be opened; status shows pending, clean, or quarantined.",
        "file को खोले जाने से पहले scan किया जाता है; status pending, clean, या quarantined दिखाता है।",
        "file उघडण्यापूर्वी ती scan केली जाते; status pending, clean किंवा quarantined दाखवते.",
        "File open hone se pehle scan hoti hai; status pending, clean, ya quarantined dikhata hai.",
    ),
    "service-evidence.steps.3.label": (
        "View / Download", "देखें / डाउनलोड करें", "पहा / डाउनलोड करा", "View / Download Karein",
    ),
    "service-evidence.steps.3.caption": (
        "Preview inline for images, video, and PDFs, or download once the scan clears.",
        "images, video, और PDFs के लिए inline preview करें, या scan clear होते ही download करें।",
        "images, video आणि PDFs साठी inline preview करा, किंवा scan clear झाल्यावर download करा.",
        "Images, video, aur PDFs ke liye inline preview karein, ya scan clear hote hi download karein.",
    ),
    "service-evidence.fieldRules.0.name": (
        "Work Order", "वर्क ऑर्डर", "वर्क ऑर्डर", "Work Order",
    ),
    "service-evidence.fieldRules.0.description": (
        "Determines which asset the evidence list — and any new upload — belongs to.",
        "यह तय करता है कि evidence list — और कोई भी नया upload — किस asset से संबंधित है।",
        "हे ठरवते की evidence list — आणि कोणताही नवीन upload — कोणत्या asset शी संबंधित आहे.",
        "Ye decide karta hai ki evidence list — aur koi bhi naya upload — kis asset se belong karta hai.",
    ),
    "service-evidence.fieldRules.1.name": (
        "File", "फ़ाइल", "फाइल", "File",
    ),
    "service-evidence.fieldRules.1.description": (
        "Photo, video (mp4/mov/webm), or document up to 100 MB; the only mandatory field on the upload form.",
        "Photo, video (mp4/mov/webm), या document, अधिकतम 100 MB तक; upload form पर यही एकमात्र अनिवार्य field है।",
        "Photo, video (mp4/mov/webm), किंवा document, जास्तीत जास्त 100 MB पर्यंत; upload form वरील हे एकमेव अनिवार्य field आहे.",
        "Photo, video (mp4/mov/webm), ya document, max 100 MB tak; upload form par yahi ek mandatory field hai.",
    ),
    "service-evidence.fieldRules.2.name": (
        "Description", "विवरण", "वर्णन", "Description",
    ),
    "service-evidence.fieldRules.2.description": (
        "Optional free-text context; the work order number is prefixed automatically when saved.",
        "वैकल्पिक free-text संदर्भ; save करने पर work order number अपने आप prefix हो जाता है।",
        "पर्यायी free-text संदर्भ; save केल्यावर work order number आपोआप prefix होतो.",
        "Optional free-text context; save karte waqt work order number automatically prefix ho jaata hai.",
    ),
    "service-evidence.fieldRules.3.name": (
        "Scan Status", "स्कैन स्टेटस", "स्कॅन स्टेटस", "Scan Status",
    ),
    "service-evidence.fieldRules.3.description": (
        "Read-only badge set by the backend malware scan (pending/clean/quarantined) — not user-editable.",
        "backend malware scan द्वारा सेट किया गया read-only badge (pending/clean/quarantined) — user द्वारा edit नहीं किया जा सकता।",
        "backend malware scan द्वारे सेट केलेला read-only badge (pending/clean/quarantined) — user कडून edit करता येत नाही.",
        "Backend malware scan dwara set kiya gaya read-only badge (pending/clean/quarantined) — user edit nahi kar sakta.",
    ),
    "service-evidence.tip.title": (
        "Uploads are permanent",
        "Uploads स्थायी होते हैं",
        "Uploads कायमस्वरूपी असतात",
        "Uploads Permanent Hote Hain",
    ),
    "service-evidence.tip.body": (
        "There's no delete or replace here — every upload stays in the repository for good, even repeat uploads for the same job. Double-check the file before confirming, and if Preview says the file is still being scanned, just retry it in a few seconds.",
        "यहाँ delete या replace करने का विकल्प नहीं है — हर upload हमेशा के लिए repository में रहता है, चाहे उसी job के लिए दोहराया गया upload ही क्यों न हो। confirm करने से पहले file को दोबारा जांच लें, और अगर Preview कहे कि file अभी भी scan हो रही है, तो कुछ सेकंड बाद फिर से try करें।",
        "इथे delete किंवा replace करण्याचा पर्याय नाही — प्रत्येक upload कायमचा repository मध्ये राहतो, अगदी त्याच job साठी पुन्हा केलेला upload असला तरीही. confirm करण्यापूर्वी file पुन्हा तपासा, आणि जर Preview म्हणत असेल की file अजूनही scan होत आहे, तर काही सेकंदांनी पुन्हा try करा.",
        "Yahan delete ya replace karne ka option nahi hai — har upload hamesha ke liye repository mein rehta hai, chahe wo usi job ke liye repeat upload hi kyun na ho. Confirm karne se pehle file ko double-check kar lein, aur agar Preview bataye ki file abhi bhi scan ho rahi hai, to bas kuch seconds baad retry kar lein.",
    ),
}


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 SERVICE_EVIDENCE.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(SERVICE_EVIDENCE)} service-evidence keys.")


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