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

Usage: docker compose exec api python seed_translations_pageinfo_tag_management.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)
TAG_MANAGEMENT = {
    "tag-management.title": (
        "Tag Management",
        "टैग प्रबंधन",
        "टॅग व्यवस्थापन",
        "Tag Management",
    ),
    "tag-management.subtitle": (
        "Issue, scan, and track the physical tags stuck to your assets",
        "अपने assets पर लगे भौतिक tags को जारी करें, स्कैन करें और ट्रैक करें",
        "तुमच्या assets वर लावलेल्या भौतिक tags जारी करा, स्कॅन करा आणि ट्रॅक करा",
        "Apne assets par lage physical tags ko issue karein, scan karein aur track karein",
    ),
    "tag-management.body.0": (
        "Manage the QR / barcode / RFID tags on your assets.",
        "अपने assets पर लगे QR / barcode / RFID tags को प्रबंधित करें।",
        "तुमच्या assets वरील QR / barcode / RFID tags व्यवस्थापित करा.",
        "Apne assets par lage QR / barcode / RFID tags ko manage karein.",
    ),
    "tag-management.body.1": (
        "Create tags for many assets at once, find assets that have moved from where they should be, and verify tags.",
        "एक साथ कई assets के लिए tags बनाएं, उन assets को खोजें जो अपनी तय जगह से हट गए हैं, और tags को verify करें।",
        "एकाच वेळी अनेक assets साठी tags तयार करा, जे assets त्यांच्या नेमलेल्या जागेवरून हलले आहेत ते शोधा, आणि tags verify करा.",
        "Ek saath kai assets ke liye tags banayein, un assets ko dhoondhein jo apni tay jagah se hat gaye hain, aur tags verify karein.",
    ),
    "tag-management.stepsHeading": (
        "How tagging works",
        "टैगिंग कैसे काम करती है",
        "टॅगिंग कसे कार्य करते",
        "Tagging kaise kaam karti hai",
    ),
    "tag-management.steps.0.label": ("Create Tags", "टैग बनाएं", "टॅग तयार करा", "Tags Banayein"),
    "tag-management.steps.0.caption": (
        "Issue a QR, barcode, RFID or NFC tag for one or many assets at once.",
        "एक या कई assets के लिए एक साथ QR, barcode, RFID या NFC tag जारी करें।",
        "एक किंवा अनेक assets साठी एकाच वेळी QR, barcode, RFID किंवा NFC tag जारी करा.",
        "Ek ya kai assets ke liye ek saath QR, barcode, RFID ya NFC tag issue karein.",
    ),
    "tag-management.steps.1.label": ("Record Scan", "स्कैन दर्ज करें", "स्कॅन नोंदवा", "Scan Record Karein"),
    "tag-management.steps.1.caption": (
        "Log that a tag was scanned, live in the field or uploaded later from an offline device.",
        "यह दर्ज करें कि tag स्कैन किया गया — फ़ील्ड में लाइव या बाद में offline device से अपलोड किया गया।",
        "tag स्कॅन झाल्याची नोंद करा — फील्डमध्ये लाईव्ह किंवा नंतर offline डिव्हाइसवरून अपलोड केलेली.",
        "Ye log karein ki tag scan hua — field mein live ya baad mein offline device se upload kiya gaya.",
    ),
    "tag-management.steps.2.label": ("Flag Displaced", "विस्थापित के रूप में चिह्नित करें", "विस्थापित म्हणून चिन्हांकित करा", "Displaced Flag Karein"),
    "tag-management.steps.2.caption": (
        "If the scan location doesn't match the asset's assigned location, it's flagged as displaced.",
        "यदि scan location, asset की assigned location से मेल नहीं खाती, तो इसे displaced के रूप में फ़्लैग कर दिया जाता है।",
        "जर scan location, asset च्या assigned location शी जुळत नसेल, तर ती displaced म्हणून फ्लॅग केली जाते.",
        "Agar scan location, asset ki assigned location se match nahi karti, to use displaced flag kar diya jaata hai.",
    ),
    "tag-management.steps.3.label": ("Resolve / Verify", "समाधान / सत्यापन", "निराकरण / पडताळणी", "Resolve / Verify"),
    "tag-management.steps.3.caption": (
        "Look up the full record by tag when signed in, or just the public basics with no login.",
        "sign in होने पर tag से पूरा record देखें, या बिना login के केवल सार्वजनिक बुनियादी जानकारी।",
        "sign in केलेले असल्यास tag द्वारे संपूर्ण record पहा, किंवा login शिवाय फक्त सार्वजनिक मूलभूत माहिती.",
        "Sign in hone par tag se full record dekhein, ya bina login ke sirf public basic details.",
    ),
    "tag-management.fieldRules.0.name": ("Asset ID(s)", "Asset ID(s)", "Asset ID(s)", "Asset ID(s)"),
    "tag-management.fieldRules.0.description": (
        "One asset ID per line or comma-separated; at least one is required before you can issue a batch.",
        "प्रति line एक asset ID या comma से अलग करें; batch जारी करने से पहले कम से कम एक ज़रूरी है।",
        "प्रत्येक line मध्ये एक asset ID किंवा comma ने वेगळे करा; batch जारी करण्यापूर्वी किमान एक आवश्यक आहे.",
        "Har line mein ek asset ID ya comma-separated; batch issue karne se pehle kam se kam ek zaroori hai.",
    ),
    "tag-management.fieldRules.1.name": ("Tag Medium", "Tag Medium", "Tag Medium", "Tag Medium"),
    "tag-management.fieldRules.1.description": (
        "QR, barcode, RFID or NFC — sets what kind of physical tag is generated for every asset in the batch.",
        "QR, barcode, RFID या NFC — यह तय करता है कि batch के हर asset के लिए किस तरह का physical tag जनरेट होगा।",
        "QR, barcode, RFID किंवा NFC — batch मधील प्रत्येक asset साठी कोणत्या प्रकारचा physical tag तयार होईल हे ठरवते.",
        "QR, barcode, RFID ya NFC — ye decide karta hai ki batch ke har asset ke liye kaisa physical tag generate hoga.",
    ),
    "tag-management.fieldRules.2.name": ("Tag ID", "Tag ID", "Tag ID", "Tag ID"),
    "tag-management.fieldRules.2.description": (
        "Identifies one physical tag; required to Resolve, Verify or Record a Scan.",
        "एक physical tag की पहचान करता है; Resolve, Verify या Record a Scan के लिए ज़रूरी है।",
        "एक physical tag ओळखते; Resolve, Verify किंवा Record a Scan साठी आवश्यक आहे.",
        "Ek physical tag ko identify karta hai; Resolve, Verify ya Record a Scan ke liye zaroori hai.",
    ),
    "tag-management.fieldRules.3.name": ("Compare Location", "Compare Location", "Compare Location", "Compare Location"),
    "tag-management.fieldRules.3.description": (
        "When ticked, the scan's location is checked against the asset's assigned location — a mismatch flags the asset as Displaced.",
        "टिक करने पर, scan की location को asset की assigned location से जांचा जाता है — बेमेल होने पर asset को Displaced के रूप में फ़्लैग किया जाता है।",
        "टिक केल्यास, scan ची location asset च्या assigned location सोबत तपासली जाते — जुळत नसल्यास asset ला Displaced म्हणून फ्लॅग केले जाते.",
        "Tick karne par, scan ki location ko asset ki assigned location se check kiya jaata hai — mismatch hone par asset ko Displaced flag kar diya jaata hai.",
    ),
    "tag-management.fieldRules.4.name": ("GTIN", "GTIN", "GTIN", "GTIN"),
    "tag-management.fieldRules.4.description": (
        "8/12/13/14-digit product barcode number; validated against its check digit before you trust it.",
        "8/12/13/14-अंकों की product barcode number; भरोसा करने से पहले इसके check digit के विरुद्ध validate किया जाता है।",
        "8/12/13/14-अंकी product barcode number; विश्वास ठेवण्यापूर्वी त्याच्या check digit विरुद्ध validate केली जाते.",
        "8/12/13/14-digit product barcode number; trust karne se pehle iske check digit ke against validate kiya jaata hai.",
    ),
    "tag-management.tip.title": (
        "Use IDs, not asset refs",
        "IDs का उपयोग करें, asset refs का नहीं",
        "IDs वापरा, asset refs नाही",
        "IDs use karein, asset refs nahi",
    ),
    "tag-management.tip.body": (
        "Create Tags (Bulk) expects each asset's internal ID (a UUID), not its human asset_ref code like AS-001 — typing refs will fail per row in the results table. Use Select From Asset List to pick assets instead of typing IDs by hand.",
        "Create Tags (Bulk), हर asset की internal ID (एक UUID) मांगता है, न कि AS-001 जैसा human asset_ref code — refs टाइप करने पर results table में हर row के लिए यह fail हो जाएगा। हाथ से IDs टाइप करने के बजाय assets चुनने के लिए Select From Asset List का उपयोग करें।",
        "Create Tags (Bulk) प्रत्येक asset ची internal ID (एक UUID) अपेक्षित असते, AS-001 सारखा human asset_ref code नाही — refs टाइप केल्यास results table मध्ये प्रत्येक row साठी ते fail होईल. हाताने IDs टाइप करण्याऐवजी assets निवडण्यासाठी Select From Asset List वापरा.",
        "Create Tags (Bulk) har asset ki internal ID (ek UUID) expect karta hai, na ki AS-001 jaisa human asset_ref code — refs type karne par results table mein har row ke liye fail ho jaayega. Hath se IDs type karne ke bajaye assets pick karne ke liye Select From Asset List 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 TAG_MANAGEMENT.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(TAG_MANAGEMENT)} tag-management keys.")


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