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

Usage: docker compose exec api python seed_translations_pageinfo_assigned_work_orders.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)
ASSIGNED_WORK_ORDERS = {
    "assigned-work-orders.title": (
        "Assigned Work Orders",
        "असाइन किए गए वर्क ऑर्डर",
        "असाइन केलेले वर्क ऑर्डर",
        "Assigned Work Orders",
    ),
    "assigned-work-orders.subtitle": (
        "Technician queue for preventive, corrective, inspection and emergency jobs",
        "प्रिवेंटिव, करेक्टिव, इंस्पेक्शन और इमरजेंसी जॉब्स के लिए टेक्नीशियन क्यू",
        "प्रिव्हेंटिव्ह, करेक्टिव्ह, इन्स्पेक्शन आणि इमर्जन्सी जॉब्जसाठी टेक्निशियन क्यू",
        "Preventive, corrective, inspection aur emergency jobs ke liye technician queue.",
    ),
    "assigned-work-orders.body.0": (
        "Lists the maintenance jobs assigned to you, with the asset, priority, due date and status of each. Use Log New Work Order (if you have work_order:create permission) to raise and assign a job against a real asset from the asset register.",
        "आपको सौंपे गए मेंटेनेंस जॉब्स को सूचीबद्ध करता है, साथ ही प्रत्येक का asset, priority, due date और status भी दिखाता है। यदि आपके पास work_order:create permission है, तो asset register के किसी वास्तविक asset के विरुद्ध जॉब बनाने और असाइन करने के लिए Log New Work Order का उपयोग करें।",
        "तुम्हाला नेमून दिलेल्या मेंटेनन्स जॉब्जची यादी दाखवते, प्रत्येकाच्या asset, priority, due date आणि status सह. जर तुमच्याकडे work_order:create permission असेल, तर asset register मधील एखाद्या प्रत्यक्ष asset विरुद्ध जॉब तयार करून असाइन करण्यासाठी Log New Work Order वापरा.",
        "Aapko assign kiye gaye maintenance jobs ki list dikhata hai, saath mein har ek ka asset, priority, due date aur status. Agar aapke paas work_order:create permission hai, to asset register ke kisi real asset ke against job raise aur assign karne ke liye Log New Work Order use karein.",
    ),
    "assigned-work-orders.body.1": (
        "Row actions drive the job through its lifecycle: Start, Pause, Resume and Mark Completed only appear for the statuses they apply to.",
        "Row actions जॉब को उसके lifecycle के दौरान आगे बढ़ाते हैं: Start, Pause, Resume और Mark Completed केवल उन्हीं statuses के लिए दिखाई देते हैं जिन पर वे लागू होते हैं।",
        "Row actions जॉबला त्याच्या lifecycle मधून पुढे नेतात: Start, Pause, Resume आणि Mark Completed फक्त त्या statuses साठीच दिसतात ज्यांना ते लागू होतात.",
        "Row actions job ko uske lifecycle ke through le jaate hain: Start, Pause, Resume aur Mark Completed sirf un statuses ke liye dikhte hain jin par ye apply hote hain.",
    ),
    "assigned-work-orders.stepsHeading": (
        "Work order lifecycle",
        "वर्क ऑर्डर लाइफसाइकल",
        "वर्क ऑर्डर लाइफसायकल",
        "Work order lifecycle",
    ),
    "assigned-work-orders.steps.0.label": ("Assigned", "असाइन किया गया", "असाइन केलेले", "Assigned"),
    "assigned-work-orders.steps.0.caption": (
        "Created and assigned to a technician; not yet started",
        "बनाया गया और एक technician को असाइन किया गया; अभी शुरू नहीं हुआ",
        "तयार करून एका technician ला असाइन केले आहे; अद्याप सुरू झालेले नाही",
        "Create hokar ek technician ko assign kiya gaya hai; abhi start nahi hua",
    ),
    "assigned-work-orders.steps.1.label": ("In Progress", "प्रगति में", "प्रगतीपथावर", "In Progress"),
    "assigned-work-orders.steps.1.caption": (
        "Technician pressed Start; work is underway",
        "Technician ने Start दबाया; काम चल रहा है",
        "Technician ने Start दाबले; काम सुरू आहे",
        "Technician ne Start dabaya hai; kaam chal raha hai",
    ),
    "assigned-work-orders.steps.2.label": ("On Hold", "होल्ड पर", "होल्डवर", "On Hold"),
    "assigned-work-orders.steps.2.caption": (
        "Paused (e.g. waiting on parts); Resume returns it to In Progress",
        "रोक दिया गया (जैसे, parts का इंतज़ार); Resume इसे वापस In Progress में ले जाता है",
        "थांबवले आहे (उदा. parts ची वाट पाहणे); Resume हे परत In Progress मध्ये नेते",
        "Pause kiya gaya hai (jaise parts ka wait); Resume isse wapas In Progress mein le jaata hai",
    ),
    "assigned-work-orders.steps.3.label": ("Completed", "पूर्ण", "पूर्ण", "Completed"),
    "assigned-work-orders.steps.3.caption": (
        "Marked complete from In Progress; closes the job",
        "In Progress से complete के रूप में चिह्नित किया गया; जॉब बंद हो जाता है",
        "In Progress मधून complete म्हणून चिन्हांकित केले जाते; जॉब बंद होते",
        "In Progress se complete mark kiya jaata hai; job close ho jaata hai",
    ),
    "assigned-work-orders.fieldRules.0.name": ("Asset", "Asset", "Asset", "Asset"),
    "assigned-work-orders.fieldRules.0.description": (
        "Picked from the live asset register; the work order cannot be created without one",
        "live asset register से चुना जाता है; इसके बिना work order नहीं बनाया जा सकता",
        "live asset register मधून निवडले जाते; याशिवाय work order तयार करता येत नाही",
        "Live asset register se pick kiya jaata hai; iske bina work order create nahi ho sakta",
    ),
    "assigned-work-orders.fieldRules.1.name": ("Assign To", "असाइन टू", "असाइन टू", "Assign To"),
    "assigned-work-orders.fieldRules.1.description": (
        "Technician from the user list; left blank the work order stays unassigned",
        "user list में से technician; खाली छोड़ने पर work order unassigned ही रहता है",
        "user list मधील technician; रिकामे ठेवल्यास work order unassigned राहतो",
        "User list se technician; blank chhodne par work order unassigned hi rehta hai",
    ),
    "assigned-work-orders.fieldRules.2.name": ("Work Type", "वर्क टाइप", "वर्क टाइप", "Work Type"),
    "assigned-work-orders.fieldRules.2.description": (
        "Preventive, corrective, inspection or emergency — shown as a column and filterable",
        "Preventive, corrective, inspection या emergency — एक column के रूप में दिखाया जाता है और filter किया जा सकता है",
        "Preventive, corrective, inspection किंवा emergency — column म्हणून दाखवले जाते आणि filter करता येते",
        "Preventive, corrective, inspection ya emergency — column ke roop mein dikhaya jaata hai aur filter kiya ja sakta hai",
    ),
    "assigned-work-orders.fieldRules.3.name": ("Priority", "प्राथमिकता", "प्राधान्य", "Priority"),
    "assigned-work-orders.fieldRules.3.description": (
        "Critical/High/Medium/Low; colours the priority badge and the Overdue Tasks stat",
        "Critical/High/Medium/Low; priority badge और Overdue Tasks stat को रंग देता है",
        "Critical/High/Medium/Low; priority badge आणि Overdue Tasks stat ला रंग देते",
        "Critical/High/Medium/Low; priority badge aur Overdue Tasks stat ko color karta hai",
    ),
    "assigned-work-orders.fieldRules.4.name": ("Description", "विवरण", "वर्णन", "Description"),
    "assigned-work-orders.fieldRules.4.description": (
        "Optional free-text note on the job, e.g. what to inspect or replace",
        "जॉब पर वैकल्पिक free-text नोट, जैसे क्या inspect या replace करना है",
        "जॉबवर पर्यायी free-text नोंद, उदा. काय inspect किंवा replace करायचे",
        "Job par optional free-text note, jaise kya inspect ya replace karna hai",
    ),
    "assigned-work-orders.tip.title": (
        "Paused jobs can hide from the Status filter",
        "रोकी गई जॉब्स Status filter से छिप सकती हैं",
        "थांबवलेल्या जॉब्ज Status filter मधून लपू शकतात",
        "Paused jobs Status filter se hide ho sakti hain",
    ),
    "assigned-work-orders.tip.body": (
        "Pausing a work order sets it to 'on_hold', which is not one of the Status dropdown's options (only Assigned/In Progress/Pending Parts/Completed are listed). Switch the filter back to All Statuses to find a paused job and its Resume button.",
        "किसी work order को pause करने पर उसे 'on_hold' सेट कर दिया जाता है, जो Status dropdown के options में शामिल नहीं है (केवल Assigned/In Progress/Pending Parts/Completed सूचीबद्ध हैं)। रोकी गई जॉब और उसका Resume button ढूंढने के लिए filter को वापस All Statuses पर बदलें।",
        "एखादा work order pause केल्यास तो 'on_hold' वर सेट होतो, जो Status dropdown च्या options पैकी नाही (फक्त Assigned/In Progress/Pending Parts/Completed सूचीबद्ध आहेत). थांबवलेली जॉब आणि तिचे Resume button शोधण्यासाठी filter परत All Statuses वर बदला.",
        "Kisi work order ko pause karne par wo 'on_hold' set ho jaata hai, jo Status dropdown ke options mein nahi hai (sirf Assigned/In Progress/Pending Parts/Completed listed hain). Paused job aur uska Resume button dhundne ke liye filter ko wapas All Statuses par switch 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 ASSIGNED_WORK_ORDERS.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(ASSIGNED_WORK_ORDERS)} assigned-work-orders keys.")


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