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

Usage: docker compose exec api python seed_translations_pageinfo_asset_verification.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_VERIFICATION = {
    "asset-verification.title": (
        "Asset Verification",
        "एसेट सत्यापन",
        "एसेट पडताळणी",
        "Asset Verification",
    ),
    "asset-verification.subtitle": (
        "How tag-based physical verification works",
        "टैग-आधारित भौतिक सत्यापन कैसे काम करता है",
        "टॅग-आधारित भौतिक पडताळणी कशी कार्य करते",
        "Tag-based physical verification kaise kaam karta hai",
    ),
    "asset-verification.body.0": (
        "Asset registry and tag/RFID-based physical verification.",
        "एसेट रजिस्ट्री और टैग/RFID-आधारित भौतिक सत्यापन।",
        "एसेट रजिस्ट्री आणि टॅग/RFID-आधारित भौतिक पडताळणी.",
        "Asset registry aur tag/RFID-based physical verification.",
    ),
    "asset-verification.body.1": (
        "Registry lists every tagged asset with its last known location and custodian; Verify by Tag scans a physical tag to confirm the asset is actually where the registry says it is. Each scan is logged with GPS and compared against the asset's registered location — a mismatch flags the asset as displaced and automatically raises an audit finding.",
        "रजिस्ट्री हर टैग किए गए asset को उसके अंतिम ज्ञात location और custodian के साथ सूचीबद्ध करती है; Verify by Tag एक भौतिक tag को स्कैन करके पुष्टि करता है कि asset वास्तव में वहीं है जहाँ रजिस्ट्री बताती है। हर scan को GPS के साथ लॉग किया जाता है और asset की registered location से तुलना की जाती है — बेमेल होने पर asset को displaced के रूप में फ़्लैग किया जाता है और स्वतः एक audit finding उठाई जाती है।",
        "रजिस्ट्री प्रत्येक टॅग केलेल्या asset ला त्याच्या शेवटच्या ज्ञात location आणि custodian सह सूचीबद्ध करते; Verify by Tag एक भौतिक tag स्कॅन करून खात्री करते की asset खरोखर तिथेच आहे जिथे रजिस्ट्री सांगते. प्रत्येक scan GPS सह लॉग केला जातो आणि asset च्या registered location शी तुलना केली जाते — जुळत नसल्यास asset displaced म्हणून फ्लॅग होते आणि आपोआप एक audit finding तयार होते.",
        "Registry har tagged asset ko uski last known location aur custodian ke saath list karti hai; Verify by Tag ek physical tag scan karke confirm karta hai ki asset waqai wahi hai jahan registry batati hai. Har scan GPS ke saath log hota hai aur asset ki registered location se compare kiya jaata hai — mismatch hone par asset ko displaced flag kiya jaata hai aur automatically ek audit finding raise ho jaati hai.",
    ),
    "asset-verification.stepsHeading": (
        "What happens on a scan",
        "स्कैन करने पर क्या होता है",
        "स्कॅन केल्यावर काय होते",
        "Scan karne par kya hota hai",
    ),
    "asset-verification.steps.0.label": ("Scan Tag", "टैग स्कैन करें", "टॅग स्कॅन करा", "Tag Scan Karo"),
    "asset-verification.steps.0.caption": (
        "Enter or scan the QR/RFID tag ID",
        "QR/RFID tag ID दर्ज करें या स्कैन करें",
        "QR/RFID tag ID टाका किंवा स्कॅन करा",
        "QR/RFID tag ID enter ya scan karo",
    ),
    "asset-verification.steps.1.label": ("Resolve Asset", "एसेट रिज़ॉल्व करें", "एसेट रिझॉल्व्ह करा", "Asset Resolve Karo"),
    "asset-verification.steps.1.caption": (
        "Tag is matched to its asset record",
        "Tag को उसके asset record से मिलान किया जाता है",
        "Tag त्याच्या asset record शी जुळवला जातो",
        "Tag ko uske asset record se match kiya jaata hai",
    ),
    "asset-verification.steps.2.label": ("Capture Location", "लोकेशन कैप्चर करें", "लोकेशन कॅप्चर करा", "Location Capture Karo"),
    "asset-verification.steps.2.caption": (
        "Device GPS auto-fills lat/lng",
        "डिवाइस GPS स्वतः lat/lng भर देता है",
        "डिव्हाइस GPS आपोआप lat/lng भरते",
        "Device GPS auto lat/lng fill kar deta hai",
    ),
    "asset-verification.steps.3.label": ("Check Geofence", "जियोफ़ेंस जाँचें", "जिओफेन्स तपासा", "Geofence Check Karo"),
    "asset-verification.steps.3.caption": (
        "Compared against the registered location",
        "Registered location से तुलना की जाती है",
        "Registered location शी तुलना केली जाते",
        "Registered location se compare kiya jaata hai",
    ),
    "asset-verification.steps.4.label": ("Verified or Displaced", "सत्यापित या विस्थापित", "पडताळलेले किंवा विस्थापित", "Verified ya Displaced"),
    "asset-verification.steps.4.caption": (
        "Displacement auto-raises an audit finding",
        "विस्थापन (displacement) स्वतः एक audit finding उठाता है",
        "विस्थापन (displacement) आपोआप एक audit finding तयार करते",
        "Displacement automatically ek audit finding raise karta hai",
    ),
    "asset-verification.fieldRules.0.name": ("Tag ID", "टैग आईडी", "टॅग आयडी", "Tag ID"),
    "asset-verification.fieldRules.0.description": (
        "The QR/RFID code printed on the asset; resolved server-side to its asset record.",
        "Asset पर छपा हुआ QR/RFID कोड; server-side पर इसके asset record से resolve किया जाता है।",
        "Asset वर छापलेला QR/RFID कोड; server-side वर त्याच्या asset record शी resolve केला जातो.",
        "Asset par printed QR/RFID code; server-side par iske asset record se resolve kiya jaata hai.",
    ),
    "asset-verification.fieldRules.1.name": ("Latitude / Longitude", "अक्षांश / देशांतर", "अक्षांश / रेखांश", "Latitude / Longitude"),
    "asset-verification.fieldRules.1.description": (
        "Auto-captured from the device on entering this tab; falls back to the map picker if GPS permission is denied.",
        "इस tab में आने पर डिवाइस से स्वतः कैप्चर होता है; GPS permission अस्वीकृत होने पर map picker पर वापस चला जाता है।",
        "या tab मध्ये आल्यावर डिव्हाइसवरून आपोआप कॅप्चर होते; GPS permission नाकारल्यास map picker वर परत जाते.",
        "Is tab mein aane par device se auto-capture hota hai; GPS permission deny hone par map picker par fallback ho jaata hai.",
    ),
    "asset-verification.fieldRules.2.name": ("Lifecycle", "लाइफ़साइकल", "लाइफसायकल", "Lifecycle"),
    "asset-verification.fieldRules.2.description": (
        "Registry column showing the asset's current lifecycle state (e.g. active, disposed).",
        "रजिस्ट्री का column जो asset की वर्तमान lifecycle state (जैसे active, disposed) दिखाता है।",
        "रजिस्ट्रीचा column जो asset ची सध्याची lifecycle state (उदा. active, disposed) दाखवतो.",
        "Registry ka column jo asset ki current lifecycle state (jaise active, disposed) dikhata hai.",
    ),
    "asset-verification.tip.title": (
        "Displacement raises a finding automatically",
        "विस्थापन स्वतः एक finding उठाता है",
        "विस्थापन आपोआप एक finding तयार करते",
        "Displacement automatically ek finding raise karta hai",
    ),
    "asset-verification.tip.body": (
        "If the scanned GPS falls outside the asset's registered geofence, the scan is still recorded as verified but flagged 'displaced' and an audit finding is created without any extra step — there's no separate 'report displacement' action to remember.",
        "यदि scan की गई GPS asset की registered geofence के बाहर पड़ती है, तो scan फिर भी verified के रूप में दर्ज होता है लेकिन 'displaced' के रूप में flag हो जाता है और बिना किसी अतिरिक्त कदम के एक audit finding बन जाती है — याद रखने के लिए कोई अलग 'report displacement' action नहीं है।",
        "जर स्कॅन केलेली GPS asset च्या registered geofence च्या बाहेर पडली, तर scan तरीही verified म्हणून नोंदवला जातो पण 'displaced' म्हणून फ्लॅग होतो आणि कोणत्याही अतिरिक्त पायरीशिवाय एक audit finding तयार होते — लक्षात ठेवण्यासाठी वेगळी 'report displacement' क्रिया नाही.",
        "Agar scanned GPS asset ki registered geofence ke bahar padta hai, to scan phir bhi verified record hota hai lekin 'displaced' flag ho jaata hai aur bina kisi extra step ke ek audit finding create ho jaati hai — yaad rakhne ke liye koi separate 'report displacement' action nahi hai.",
    ),
}


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_VERIFICATION.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_VERIFICATION)} asset-verification keys.")


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