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

Usage: docker compose exec api python seed_translations_pageinfo_warehouse_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)
WAREHOUSE_MANAGEMENT = {
    "warehouse-management.title": (
        "Stock by Location",
        "स्टॉक बाय लोकेशन",
        "स्टॉक बाय लोकेशन",
        "Stock by Location",
    ),
    "warehouse-management.subtitle": (
        "How stock for one item breaks down across locations",
        "एक item का stock विभिन्न locations में कैसे विभाजित होता है",
        "एका item चा stock विविध locations मध्ये कसा विभागला जातो",
        "Ek item ka stock alag-alag locations mein kaise divide hota hai",
    ),
    "warehouse-management.body.0": (
        "Real stock levels per item, grouped by location.",
        "प्रत्येक item के वास्तविक stock levels, location के अनुसार समूहीकृत।",
        "प्रत्येक item चे प्रत्यक्ष stock levels, location नुसार गटबद्ध.",
        "Har item ke real stock levels, location ke hisaab se group kiye gaye hain.",
    ),
    "warehouse-management.body.1": (
        "There is no separate warehouse/bin model in this system — location is a direct reference to the Locations master.",
        "इस सिस्टम में अलग warehouse/bin मॉडल नहीं है — location सीधे Locations master का संदर्भ है।",
        "या सिस्टममध्ये स्वतंत्र warehouse/bin मॉडेल नाही — location हा थेट Locations master चा संदर्भ आहे.",
        "Is system mein alag se warehouse/bin model nahi hai — location seedha Locations master ka reference hota hai.",
    ),
    "warehouse-management.stepsHeading": (
        "How to read this view",
        "इस व्यू को कैसे पढ़ें",
        "हे व्ह्यू कसे वाचावे",
        "Is view ko kaise padhein",
    ),
    "warehouse-management.steps.0.label": (
        "Select Item", "आइटम चुनें", "आयटम निवडा", "Item Select Karein",
    ),
    "warehouse-management.steps.0.caption": (
        "Pick one item from the dropdown",
        "dropdown से एक item चुनें",
        "dropdown मधून एक item निवडा",
        "Dropdown se ek item choose karein",
    ),
    "warehouse-management.steps.1.label": (
        "By Location", "location अनुसार", "location नुसार", "Location ke Hisaab Se",
    ),
    "warehouse-management.steps.1.caption": (
        "One row per location holding stock",
        "स्टॉक रखने वाले प्रत्येक location के लिए एक row",
        "स्टॉक असलेल्या प्रत्येक location साठी एक row",
        "Stock rakhne wale har location ke liye ek row",
    ),
    "warehouse-management.steps.2.label": (
        "On Hand vs Reserved", "On Hand बनाम Reserved", "On Hand विरुद्ध Reserved", "On Hand vs Reserved",
    ),
    "warehouse-management.steps.2.caption": (
        "Reserved is already committed, not free",
        "Reserved पहले से committed है, free नहीं",
        "Reserved आधीच committed आहे, free नाही",
        "Reserved already committed hota hai, free nahi hai",
    ),
    "warehouse-management.steps.3.label": (
        "Check Last Count", "Last Count जाँचें", "Last Count तपासा", "Last Count Check Karein",
    ),
    "warehouse-management.steps.3.caption": (
        "Dash means never physically verified",
        "डैश (—) का मतलब है कभी physically verify नहीं हुआ",
        "डॅश (—) म्हणजे कधीही physically verify झाले नाही",
        "Dash (—) ka matlab hai kabhi physically verify nahi hua",
    ),
    "warehouse-management.fieldRules.0.name": ("Location", "लोकेशन", "लोकेशन", "Location"),
    "warehouse-management.fieldRules.0.description": (
        "Physical location from the Locations master that this stock row belongs to.",
        "वह physical location जिससे यह stock row Locations master में संबंधित है।",
        "ज्या physical location शी हा stock row Locations master मध्ये संबंधित आहे.",
        "Wo physical location jisse ye stock row Locations master mein belong karta hai.",
    ),
    "warehouse-management.fieldRules.1.name": ("Bin", "बिन", "बिन", "Bin"),
    "warehouse-management.fieldRules.1.description": (
        "Optional shelf/bin reference on the stock row; shows — when not recorded.",
        "stock row पर optional shelf/bin संदर्भ; रिकॉर्ड न होने पर — दिखाता है।",
        "stock row वर optional shelf/bin संदर्भ; रेकॉर्ड नसल्यास — दाखवते.",
        "Stock row par optional shelf/bin reference; record na hone par — dikhta hai.",
    ),
    "warehouse-management.fieldRules.2.name": ("On Hand", "ऑन हैंड", "ऑन हँड", "On Hand"),
    "warehouse-management.fieldRules.2.description": (
        "Total units physically present at this location right now.",
        "इस समय इस location पर physically मौजूद कुल units।",
        "सध्या या location वर प्रत्यक्ष उपस्थित असलेल्या एकूण units.",
        "Is waqt is location par physically present total units.",
    ),
    "warehouse-management.fieldRules.3.name": ("Reserved", "रिजर्व्ड", "रिझर्व्हड", "Reserved"),
    "warehouse-management.fieldRules.3.description": (
        "Units already committed to open requests/orders — not available to issue further.",
        "पहले से open requests/orders के लिए committed units — आगे issue करने हेतु उपलब्ध नहीं।",
        "आधीच open requests/orders साठी committed असलेल्या units — पुढे issue करण्यासाठी उपलब्ध नाहीत.",
        "Pehle se open requests/orders ke liye committed units — aage issue karne ke liye available nahi hain.",
    ),
    "warehouse-management.fieldRules.4.name": ("Last Count", "लास्ट काउंट", "लास्ट काउंट", "Last Count"),
    "warehouse-management.fieldRules.4.description": (
        "Date of the most recent physical verification for this location; — if it's never been counted.",
        "इस location के लिए सबसे हाल की physical verification की तारीख; कभी count न हुआ हो तो — दिखेगा।",
        "या location साठी सर्वात अलीकडील physical verification ची तारीख; कधीच count न झाल्यास — दिसेल.",
        "Is location ke liye sabse recent physical verification ki date; kabhi count na hua ho to — dikhega.",
    ),
    "warehouse-management.tip.title": (
        "Item dropdown caps at 200",
        "Item dropdown 200 तक सीमित है",
        "Item dropdown 200 पर्यंत मर्यादित आहे",
        "Item Dropdown 200 Tak Limited Hai",
    ),
    "warehouse-management.tip.body": (
        "The item selector loads only the first 200 inventory items. If the item you need isn't listed, look up its item code from the main Inventory list first — there's no search box here.",
        "item selector केवल पहले 200 inventory items लोड करता है। यदि आपको चाहिए वाला item सूची में नहीं है, तो पहले main Inventory list से उसका item code देखें — यहाँ कोई search box नहीं है।",
        "item selector फक्त पहिले 200 inventory items लोड करतो. जर तुम्हाला हवा असलेला item यादीत नसेल, तर आधी main Inventory list मधून त्याचा item code शोधा — इथे search box नाही.",
        "Item selector sirf pehle 200 inventory items load karta hai. Agar aapko chahiye wala item list mein nahi hai, to pehle main Inventory list se uska item code dekhein — yahan koi search box 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 WAREHOUSE_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(WAREHOUSE_MANAGEMENT)} warehouse-management keys.")


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