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

Usage: docker compose exec api python seed_translations_pageinfo_asset_inspection_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)
ASSET_INSPECTION_DETAIL = {
    "asset-inspection-detail.title": (
        "Asset Inspection Details",
        "एसेट इंस्पेक्शन डिटेल्स",
        "एसेट इन्स्पेक्शन डिटेल्स",
        "Asset Inspection Details",
    ),
    "asset-inspection-detail.subtitle": (
        "Read-only record of one scheduled, passed, or failed inspection",
        "एक scheduled, passed, या failed inspection का read-only रिकॉर्ड",
        "एका scheduled, passed, किंवा failed inspection चा read-only रेकॉर्ड",
        "Ek scheduled, passed, ya failed inspection ka read-only record",
    ),
    "asset-inspection-detail.body.0": (
        "Shows everything recorded for a single asset inspection: the asset, assigned technician, inspection date, and any notes.",
        "यह किसी एक asset inspection के लिए दर्ज हर चीज़ दिखाता है: asset, नियुक्त किया गया technician, inspection की तारीख, और कोई भी notes।",
        "हे एका asset inspection साठी नोंदवलेली प्रत्येक गोष्ट दाखवते: asset, नियुक्त केलेला technician, inspection ची तारीख, आणि कोणतेही notes.",
        "Ye ek single asset inspection ke liye record ki gayi har cheez dikhata hai: asset, assigned technician, inspection date, aur koi bhi notes.",
    ),
    "asset-inspection-detail.body.1": (
        "This screen is view-only. Outcomes are recorded from the Asset Inspection Register, not from here.",
        "यह स्क्रीन केवल देखने (view-only) के लिए है। outcomes Asset Inspection Register से दर्ज किए जाते हैं, यहाँ से नहीं।",
        "ही स्क्रीन फक्त पाहण्यासाठी (view-only) आहे. outcomes Asset Inspection Register मधून नोंदवले जातात, इथून नाही.",
        "Ye screen sirf view-only hai. Outcomes Asset Inspection Register se record hote hain, yahan se nahi.",
    ),
    "asset-inspection-detail.stepsHeading": (
        "Inspection lifecycle",
        "इंस्पेक्शन लाइफ़साइकल",
        "इन्स्पेक्शन लाइफसायकल",
        "Inspection lifecycle",
    ),
    "asset-inspection-detail.steps.0.label": (
        "Scheduled",
        "निर्धारित",
        "नियोजित",
        "Scheduled",
    ),
    "asset-inspection-detail.steps.0.caption": (
        "Created from the Register's 'Schedule New Inspection' form with an asset and date.",
        "Register के 'Schedule New Inspection' फॉर्म से asset और date के साथ बनाया गया।",
        "Register च्या 'Schedule New Inspection' फॉर्ममधून asset आणि date सह तयार केले जाते.",
        "Register ke 'Schedule New Inspection' form se asset aur date ke saath banaya jaata hai.",
    ),
    "asset-inspection-detail.steps.1.label": (
        "Performed",
        "निष्पादित",
        "निष्पादित",
        "Performed",
    ),
    "asset-inspection-detail.steps.1.caption": (
        "Technician carries out the physical check.",
        "Technician physical check करता है।",
        "Technician physical check करतो.",
        "Technician physical check karta hai.",
    ),
    "asset-inspection-detail.steps.2.label": (
        "Outcome Recorded",
        "परिणाम दर्ज",
        "निकाल नोंदवला",
        "Outcome Recorded",
    ),
    "asset-inspection-detail.steps.2.caption": (
        "Register's Pass / Fail buttons close it out as Passed or Failed.",
        "Register के Pass/Fail बटन इसे Passed या Failed के रूप में बंद कर देते हैं।",
        "Register च्या Pass/Fail बटणांमुळे ते Passed किंवा Failed म्हणून बंद केले जाते.",
        "Register ke Pass/Fail buttons ise Passed ya Failed karke close kar dete hain.",
    ),
    "asset-inspection-detail.steps.3.label": (
        "Reviewed",
        "समीक्षित",
        "पुनरावलोकन केले",
        "Reviewed",
    ),
    "asset-inspection-detail.steps.3.caption": (
        "This page shows the finalized record — no edits happen here.",
        "यह पेज finalized रिकॉर्ड दिखाता है — यहाँ कोई edit नहीं होता।",
        "हे पेज finalized रेकॉर्ड दाखवते — इथे कोणतेही edit होत नाही.",
        "Ye page finalized record dikhata hai — yahan koi edit nahi hota.",
    ),
    "asset-inspection-detail.fieldRules.0.name": (
        "Status",
        "स्थिति",
        "स्थिती",
        "Status",
    ),
    "asset-inspection-detail.fieldRules.0.description": (
        "Scheduled, Passed, or Failed — set only via the Register's Pass/Fail actions, not editable here.",
        "Scheduled, Passed, या Failed — केवल Register की Pass/Fail actions से सेट होता है, यहाँ संपादन योग्य नहीं है।",
        "Scheduled, Passed, किंवा Failed — फक्त Register च्या Pass/Fail actions द्वारे सेट होते, इथे संपादन करता येत नाही.",
        "Scheduled, Passed, ya Failed — sirf Register ki Pass/Fail actions se set hota hai, yahan edit nahi kiya ja sakta.",
    ),
    "asset-inspection-detail.fieldRules.1.name": (
        "Asset",
        "एसेट",
        "एसेट",
        "Asset",
    ),
    "asset-inspection-detail.fieldRules.1.description": (
        "The asset under inspection; mandatory at scheduling time and fixed afterward.",
        "वह asset जिसका inspection हो रहा है; scheduling के समय अनिवार्य है और बाद में fixed रहता है।",
        "ज्या asset चे inspection केले जात आहे ती; scheduling च्या वेळी अनिवार्य आहे आणि नंतर fixed राहते.",
        "Wo asset jiska inspection ho raha hai; scheduling ke time mandatory hai aur baad mein fixed rehta hai.",
    ),
    "asset-inspection-detail.fieldRules.2.name": (
        "Technician",
        "टेक्नीशियन",
        "टेक्निशियन",
        "Technician",
    ),
    "asset-inspection-detail.fieldRules.2.description": (
        "Assigned technician; shows 'Unassigned' if none was picked when scheduling.",
        "नियुक्त किया गया technician; scheduling के समय कोई न चुने जाने पर 'Unassigned' दिखाता है।",
        "नियुक्त केलेला technician; scheduling करताना कोणीही निवडले नसल्यास 'Unassigned' दाखवते.",
        "Assigned technician; agar scheduling ke time koi select nahi kiya gaya to 'Unassigned' dikhata hai.",
    ),
    "asset-inspection-detail.fieldRules.3.name": (
        "Inspection Date",
        "इंस्पेक्शन डेट",
        "इन्स्पेक्शन डेट",
        "Inspection Date",
    ),
    "asset-inspection-detail.fieldRules.3.description": (
        "The date the inspection was scheduled for or performed on.",
        "वह तारीख जिसके लिए inspection schedule किया गया था या जिस दिन यह किया गया।",
        "ज्या तारखेसाठी inspection schedule केले गेले होते किंवा ज्या दिवशी ते केले गेले.",
        "Wo date jiske liye inspection schedule kiya gaya tha ya jis din perform kiya gaya.",
    ),
    "asset-inspection-detail.fieldRules.4.name": (
        "Notes",
        "नोट्स",
        "नोट्स",
        "Notes",
    ),
    "asset-inspection-detail.fieldRules.4.description": (
        "Free-text remarks; the whole section is hidden when no notes were entered.",
        "फ्री-टेक्स्ट remarks; कोई notes दर्ज न होने पर पूरा section छिपा रहता है।",
        "फ्री-टेक्स्ट remarks; कोणतेही notes नोंदवले नसल्यास संपूर्ण section लपलेले असते.",
        "Free-text remarks; agar koi notes enter nahi kiye gaye to poora section hidden rehta hai.",
    ),
    "asset-inspection-detail.tip.title": (
        "No Pass/Fail buttons here",
        "यहाँ Pass/Fail बटन नहीं हैं",
        "इथे Pass/Fail बटणे नाहीत",
        "Yahan Pass/Fail buttons nahi hain",
    ),
    "asset-inspection-detail.tip.body": (
        "This detail page is read-only by design. To mark a scheduled inspection Passed or Failed, go back to the Asset Inspection Register and use the Pass/Fail buttons on its row.",
        "यह detail page डिज़ाइन के अनुसार read-only है। किसी scheduled inspection को Passed या Failed मार्क करने के लिए, Asset Inspection Register पर वापस जाएँ और उसकी row पर मौजूद Pass/Fail बटन का उपयोग करें।",
        "हे detail page डिझाइननुसार read-only आहे. एखादी scheduled inspection Passed किंवा Failed म्हणून मार्क करण्यासाठी, Asset Inspection Register वर परत जा आणि त्याच्या row वरील Pass/Fail बटणे वापरा.",
        "Ye detail page design ke hisaab se read-only hai. Kisi scheduled inspection ko Passed ya Failed mark karne ke liye, Asset Inspection Register par wapas jaayein aur uski row par diye Pass/Fail buttons use 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 ASSET_INSPECTION_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(ASSET_INSPECTION_DETAIL)} asset-inspection-detail keys.")


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