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

Usage: docker compose exec api python seed_translations_pageinfo_technician_dashboard.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)
TECHNICIAN_DASHBOARD = {
    "technician-dashboard.title": (
        "Technician Dashboard",
        "टेक्नीशियन डैशबोर्ड",
        "टेक्निशियन डॅशबोर्ड",
        "Technician Dashboard",
    ),
    "technician-dashboard.subtitle": (
        "Your work queue for today — assigned jobs, inspections due, and open breakdowns.",
        "आज के लिए आपकी work queue — assigned jobs, due inspections, और open breakdowns।",
        "आजसाठी तुमची work queue — assigned jobs, due inspections आणि open breakdowns.",
        "Aaj ke liye aapki work queue — assigned jobs, due inspections, aur open breakdowns.",
    ),
    "technician-dashboard.body.0": (
        "This is your personal work queue, not a management report — every KPI, task, and activity entry on it is scoped to work orders assigned to you.",
        "यह आपकी personal work queue है, management report नहीं — इस पर हर KPI, task, और activity entry केवल आपको assigned work orders तक सीमित है।",
        "ही तुमची personal work queue आहे, management report नाही — यावरील प्रत्येक KPI, task आणि activity entry फक्त तुम्हाला assigned असलेल्या work orders पुरती मर्यादित आहे.",
        "Ye aapki personal work queue hai, management report nahi — isme har KPI, task, aur activity entry sirf aapko assigned work orders tak scoped hai.",
    ),
    "technician-dashboard.body.1": (
        "The KPI tiles, Pending Tasks list, and Recent Activity feed each load independently, so a permissions gap or empty dataset in one section never blanks the rest of the dashboard.",
        "KPI tiles, Pending Tasks list, और Recent Activity feed — तीनों स्वतंत्र रूप से load होते हैं, इसलिए किसी एक section में permission gap या empty dataset होने पर बाकी dashboard खाली नहीं होता।",
        "KPI tiles, Pending Tasks list आणि Recent Activity feed हे तिघेही स्वतंत्रपणे load होतात, त्यामुळे एका section मध्ये permission gap किंवा empty dataset असल्यास उर्वरित dashboard रिकामा होत नाही.",
        "KPI tiles, Pending Tasks list, aur Recent Activity feed teeno independently load hote hain, isliye ek section mein permission gap ya empty dataset hone par baaki dashboard blank nahi hota.",
    ),
    "technician-dashboard.stepsHeading": (
        "Work order lifecycle",
        "Work order lifecycle",
        "Work order lifecycle",
        "Work order lifecycle",
    ),
    "technician-dashboard.steps.0.label": (
        "Assigned",
        "Assigned",
        "Assigned",
        "Assigned",
    ),
    "technician-dashboard.steps.0.caption": (
        "New work order appears in Pending Tasks with a Start button.",
        "नया work order Start button के साथ Pending Tasks में दिखाई देता है।",
        "नवीन work order Start बटणासह Pending Tasks मध्ये दिसतो.",
        "Naya work order Start button ke saath Pending Tasks mein dikhta hai.",
    ),
    "technician-dashboard.steps.1.label": (
        "In Progress",
        "In Progress",
        "In Progress",
        "In Progress",
    ),
    "technician-dashboard.steps.1.caption": (
        "After Start, a Complete button replaces it.",
        "Start करने के बाद, उसकी जगह Complete button आ जाता है।",
        "Start केल्यानंतर, त्याजागी Complete बटण येते.",
        "Start karne ke baad, uski jagah Complete button aa jaata hai.",
    ),
    "technician-dashboard.steps.2.label": (
        "Completed",
        "Completed",
        "Completed",
        "Completed",
    ),
    "technician-dashboard.steps.2.caption": (
        "Task drops off your queue and posts to Recent Activity.",
        "Task आपकी queue से हट जाता है और Recent Activity में दर्ज हो जाता है।",
        "Task तुमच्या queue मधून निघून जाते आणि Recent Activity मध्ये नोंदवले जाते.",
        "Task aapki queue se hat jaata hai aur Recent Activity mein post ho jaata hai.",
    ),
    "technician-dashboard.fieldRules.0.name": (
        "WO Number",
        "WO नंबर",
        "WO नंबर",
        "WO Number",
    ),
    "technician-dashboard.fieldRules.0.description": (
        "Unique work order code; use View All to open full detail on Assigned Work Orders.",
        "अद्वितीय work order code; Assigned Work Orders पर पूरा detail खोलने के लिए View All का उपयोग करें।",
        "अद्वितीय work order code; Assigned Work Orders वर संपूर्ण detail उघडण्यासाठी View All वापरा.",
        "Unique work order code hota hai; Assigned Work Orders par full detail kholne ke liye View All use karein.",
    ),
    "technician-dashboard.fieldRules.1.name": (
        "Asset / Type / Priority",
        "Asset / Type / Priority",
        "Asset / Type / Priority",
        "Asset / Type / Priority",
    ),
    "technician-dashboard.fieldRules.1.description": (
        "Which equipment, the work type (preventive, corrective, etc.), and its priority for triage.",
        "कौन-सा equipment, work type (preventive, corrective, आदि), और triage के लिए उसकी priority।",
        "कोणते equipment, work type (preventive, corrective, इ.) आणि triage साठी त्याची priority.",
        "Kaunsa equipment, work type (preventive, corrective, etc.), aur triage ke liye uski priority.",
    ),
    "technician-dashboard.fieldRules.2.name": (
        "Status badge",
        "Status badge",
        "Status badge",
        "Status badge",
    ),
    "technician-dashboard.fieldRules.2.description": (
        "Shows assigned, in progress, or completed — replaced by a red Overdue flag once the due date passes, regardless of status.",
        "assigned, in progress, या completed दिखाता है — due date निकलने पर status चाहे जो भी हो, इसकी जगह लाल Overdue flag आ जाता है।",
        "assigned, in progress किंवा completed दाखवते — due date उलटल्यावर status काहीही असो, त्याजागी लाल Overdue flag येते.",
        "Assigned, in progress, ya completed dikhata hai — due date nikalne par status chahe jo bhi ho, uski jagah red Overdue flag aa jaata hai.",
    ),
    "technician-dashboard.fieldRules.3.name": (
        "Start / Complete action",
        "Start / Complete action",
        "Start / Complete action",
        "Start / Complete action",
    ),
    "technician-dashboard.fieldRules.3.description": (
        "Start only shows on assigned tasks; Complete only shows on in-progress tasks — never both at once.",
        "Start केवल assigned tasks पर दिखता है; Complete केवल in-progress tasks पर दिखता है — दोनों एक साथ कभी नहीं दिखते।",
        "Start फक्त assigned tasks वर दिसते; Complete फक्त in-progress tasks वर दिसते — दोन्ही एकाच वेळी कधीही दिसत नाहीत.",
        "Start sirf assigned tasks par dikhta hai; Complete sirf in-progress tasks par dikhta hai — dono ek saath kabhi nahi dikhte.",
    ),
    "technician-dashboard.fieldRules.4.name": (
        "Inspections Due (7d) / Open Breakdowns",
        "Inspections Due (7d) / Open Breakdowns",
        "Inspections Due (7d) / Open Breakdowns",
        "Inspections Due (7d) / Open Breakdowns",
    ),
    "technician-dashboard.fieldRules.4.description": (
        "Same counts as PM Schedule and Breakdown Register — not editable here, drill in via Quick Actions.",
        "PM Schedule और Breakdown Register जैसे ही counts हैं — यहाँ edit नहीं किए जा सकते, Quick Actions से drill in करें।",
        "PM Schedule आणि Breakdown Register सारखेच counts आहेत — इथे edit करता येत नाहीत, Quick Actions मधून drill in करा.",
        "PM Schedule aur Breakdown Register jaise hi counts hain — yahan edit nahi ho sakte, Quick Actions se drill in karein.",
    ),
    "technician-dashboard.tip.title": (
        "An empty section isn't a broken page",
        "खाली section का मतलब खराब page नहीं है",
        "रिकामा section म्हणजे तुटलेले page नाही",
        "Khaali section ka matlab broken page nahi hai",
    ),
    "technician-dashboard.tip.body": (
        "KPIs, Pending Tasks, and Recent Activity load with independent requests — if your role lacks permission for one (e.g. the activity feed), only that section goes blank while the rest of the dashboard still works normally.",
        "KPIs, Pending Tasks, और Recent Activity स्वतंत्र requests के साथ load होते हैं — अगर आपके role के पास किसी एक (जैसे activity feed) की permission नहीं है, तो सिर्फ वही section खाली रहेगा, जबकि बाकी dashboard सामान्य रूप से काम करता रहेगा।",
        "KPIs, Pending Tasks आणि Recent Activity स्वतंत्र requests सह load होतात — जर तुमच्या role कडे एखाद्यासाठी (उदा. activity feed) permission नसेल, तर फक्त तोच section रिकामा राहील, तर उर्वरित dashboard सामान्यपणे काम करत राहील.",
        "KPIs, Pending Tasks, aur Recent Activity independent requests ke saath load hote hain — agar aapke role ke paas kisi ek (jaise activity feed) ki permission nahi hai, to sirf wahi section blank rahega, jabki baaki dashboard normally kaam karta rahega.",
    ),
}


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 TECHNICIAN_DASHBOARD.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(TECHNICIAN_DASHBOARD)} technician-dashboard keys.")


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