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

Usage: docker compose exec api python seed_translations_pageinfo_work_order_detail.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)
WORK_ORDER_DETAIL = {
    "work-order-detail.title": (
        "Work Order Details",
        "वर्क ऑर्डर विवरण",
        "वर्क ऑर्डर तपशील",
        "Work Order Details",
    ),
    "work-order-detail.subtitle": (
        "One job, one asset, and the proof it was done",
        "एक job, एक asset, और यह सिद्ध करने वाला प्रमाण कि यह पूरा हुआ",
        "एक job, एक asset, आणि हे पूर्ण झाल्याचा पुरावा",
        "Ek job, ek asset, aur ye prove karne wala proof ki kaam ho gaya",
    ),
    "work-order-detail.body.0": (
        "Full detail view for a single work order — work type, priority, assigned technician, dates, and the linked asset.",
        "एक single work order के लिए पूर्ण विवरण दृश्य — work type, priority, assigned technician, dates, और लिंक किया गया asset।",
        "एका single work order साठी संपूर्ण तपशील दृश्य — work type, priority, assigned technician, dates, आणि लिंक केलेली asset.",
        "Single work order ke liye full detail view — work type, priority, assigned technician, dates, aur linked asset.",
    ),
    "work-order-detail.body.1": (
        "Attach photos, videos or files here as proof-of-work; they're stored against the asset's document history, tagged as service evidence.",
        "यहाँ काम के प्रमाण के रूप में photos, videos या files attach करें; इन्हें asset की document history के विरुद्ध सेव किया जाता है और service evidence के रूप में tag किया जाता है।",
        "इथे कामाचा पुरावा म्हणून photos, videos किंवा files attach करा; ते asset च्या document history विरुद्ध साठवले जातात आणि service evidence म्हणून tag केले जातात.",
        "Yahan proof-of-work ke roop mein photos, videos ya files attach karein; ye asset ki document history ke against store hoti hain aur service evidence tag hoti hain.",
    ),
    "work-order-detail.stepsHeading": (
        "Job lifecycle",
        "जॉब जीवनचक्र",
        "जॉब जीवनचक्र",
        "Job lifecycle",
    ),
    "work-order-detail.steps.0.label": ("Assigned", "असाइन किया गया", "असाइन केले", "Assigned"),
    "work-order-detail.steps.0.caption": (
        "Job created and handed to a technician",
        "Job बनाया गया और technician को सौंपा गया",
        "Job तयार केली आणि technician कडे सोपवली",
        "Job create hoke technician ko handover ho gaya",
    ),
    "work-order-detail.steps.1.label": ("In Progress", "प्रगति पर", "प्रगतीपथावर", "In Progress"),
    "work-order-detail.steps.1.caption": (
        "Work is underway on the asset",
        "Asset पर काम चल रहा है",
        "Asset वर काम सुरू आहे",
        "Asset par kaam chal raha hai",
    ),
    "work-order-detail.steps.2.label": (
        "On Hold / Pending Parts",
        "होल्ड पर / पार्ट्स लंबित",
        "होल्डवर / पार्ट्स प्रलंबित",
        "On Hold / Pending Parts",
    ),
    "work-order-detail.steps.2.caption": (
        "Paused — waiting on parts or approval",
        "रुका हुआ — parts या approval का इंतज़ार",
        "थांबलेले — parts किंवा approval ची वाट पाहत आहे",
        "Paused — parts ya approval ka wait ho raha hai",
    ),
    "work-order-detail.steps.3.label": ("Completed", "पूर्ण", "पूर्ण", "Completed"),
    "work-order-detail.steps.3.caption": (
        "Job closed, evidence attached",
        "Job बंद, evidence attach किया गया",
        "Job बंद, evidence attach केले",
        "Job close ho gaya, evidence attach ho gaya",
    ),
    "work-order-detail.fieldRules.0.name": ("Priority", "प्राथमिकता", "प्राधान्य", "Priority"),
    "work-order-detail.fieldRules.0.description": (
        "Critical / High / Medium / Low — drives ordering on the technician's assigned list.",
        "Critical / High / Medium / Low — technician की assigned list पर ordering तय करता है।",
        "Critical / High / Medium / Low — technician च्या assigned list वरील ordering ठरवते.",
        "Critical / High / Medium / Low — technician ki assigned list par ordering decide karta hai.",
    ),
    "work-order-detail.fieldRules.1.name": ("Due Date", "देय तिथि", "देय तारीख", "Due Date"),
    "work-order-detail.fieldRules.1.description": (
        "Past this date with an open status, the job is flagged Overdue at the top of this page.",
        "यह तिथि बीत जाने पर यदि status open है, तो job इस पेज के शीर्ष पर Overdue के रूप में फ़्लैग हो जाता है।",
        "ही तारीख उलटल्यावर status open असल्यास, job या पेजच्या वर Overdue म्हणून फ्लॅग होते.",
        "Is date ke baad agar status open hai, to job is page ke top par Overdue flag ho jaata hai.",
    ),
    "work-order-detail.fieldRules.2.name": (
        "Photo, video or file",
        "फ़ोटो, वीडियो या फ़ाइल",
        "फोटो, व्हिडिओ किंवा फाइल",
        "Photo, video ya file",
    ),
    "work-order-detail.fieldRules.2.description": (
        "Required to submit the evidence form — image, video (mp4/mov/webm) or document, up to 100 MB.",
        "Evidence form सबमिट करने के लिए ज़रूरी — image, video (mp4/mov/webm) या document, 100 MB तक।",
        "Evidence form सबमिट करण्यासाठी आवश्यक — image, video (mp4/mov/webm) किंवा document, 100 MB पर्यंत.",
        "Evidence form submit karne ke liye required — image, video (mp4/mov/webm) ya document, 100 MB tak.",
    ),
    "work-order-detail.fieldRules.3.name": ("Note", "नोट", "नोंद", "Note"),
    "work-order-detail.fieldRules.3.description": (
        "Optional context saved alongside the uploaded evidence file.",
        "अपलोड की गई evidence file के साथ सेव किया गया वैकल्पिक context।",
        "अपलोड केलेल्या evidence file सोबत साठवलेला ऐच्छिक context.",
        "Uploaded evidence file ke saath save hone wala optional context.",
    ),
    "work-order-detail.tip.title": (
        "Multiple uploads for the same job",
        "एक ही job के लिए कई uploads",
        "एकाच job साठी अनेक uploads",
        "Same job ke liye multiple uploads",
    ),
    "work-order-detail.tip.body": (
        "Each evidence upload is stored as a new version rather than replacing the last, so add a photo per step (before/after) instead of trying to combine them into one file — all versions stay visible in the list.",
        "हर evidence upload पिछले को replace करने के बजाय एक नए version के रूप में सेव होता है, इसलिए सबको एक ही file में मिलाने की कोशिश करने के बजाय हर step (before/after) के लिए अलग photo जोड़ें — सभी versions list में दिखाई देते रहते हैं।",
        "प्रत्येक evidence upload मागील ला replace करण्याऐवजी नवीन version म्हणून साठवले जाते, त्यामुळे सर्व एका file मध्ये एकत्र करण्याचा प्रयत्न करण्याऐवजी प्रत्येक step (before/after) साठी वेगळा photo जोडा — सर्व versions list मध्ये दिसत राहतात.",
        "Har evidence upload last ko replace karne ke bajaye ek naya version banke store hota hai, isliye sabko ek hi file mein combine karne ki koshish karne ke bajaye har step (before/after) ke liye alag photo add karein — sab versions list mein visible rehte hain.",
    ),
}


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 WORK_ORDER_DETAIL.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(WORK_ORDER_DETAIL)} work-order-detail keys.")


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