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

Usage: docker compose exec api python seed_translations_pageinfo_location_masters.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)
LOCATION_MASTERS = {
    "location-masters.title": (
        "Location Master Registers",
        "लोकेशन मास्टर रजिस्टर",
        "लोकेशन मास्टर रजिस्टर",
        "Location Master Registers",
    ),
    "location-masters.subtitle": (
        "How this register works and what each field controls",
        "यह रजिस्टर कैसे काम करता है और प्रत्येक फ़ील्ड क्या नियंत्रित करता है",
        "हे रजिस्टर कसे कार्य करते आणि प्रत्येक फील्ड काय नियंत्रित करते",
        "Ye register kaise kaam karta hai aur har field kya control karta hai",
    ),
    "location-masters.body.0": (
        "This register defines the physical hierarchy every asset is tagged against. A location must exist and be active here before it can be selected on an asset, transfer, or audit form.",
        "यह रजिस्टर उस भौतिक पदानुक्रम को परिभाषित करता है जिसके विरुद्ध हर asset टैग किया जाता है। किसी location को asset, transfer या audit फ़ॉर्म पर चुने जाने से पहले यहाँ मौजूद और active होना ज़रूरी है।",
        "हे रजिस्टर त्या भौतिक श्रेणीरचनेची व्याख्या करते ज्याविरुद्ध प्रत्येक asset टॅग केली जाते. एखादी location asset, transfer किंवा audit फॉर्मवर निवडण्यापूर्वी येथे अस्तित्वात असणे आणि active असणे आवश्यक आहे.",
        "Ye register wo physical hierarchy define karta hai jiske against har asset tag hota hai. Kisi location ko asset, transfer, ya audit form par select karne se pehle yahan exist aur active hona zaroori hai.",
    ),
    "location-masters.stepsHeading": (
        "How the hierarchy builds",
        "पदानुक्रम कैसे बनता है",
        "श्रेणीरचना कशी तयार होते",
        "Hierarchy kaise banti hai",
    ),
    "location-masters.steps.0.label": ("Country", "देश", "देश", "Country"),
    "location-masters.steps.0.caption": ("Top level", "शीर्ष स्तर", "सर्वोच्च स्तर", "Top level"),
    "location-masters.steps.1.label": ("State", "राज्य", "राज्य", "State"),
    "location-masters.steps.1.caption": ("Region", "क्षेत्र", "प्रदेश", "Region"),
    "location-masters.steps.2.label": ("City", "शहर", "शहर", "City"),
    "location-masters.steps.2.caption": ("Site or campus", "साइट या कैंपस", "साइट किंवा कॅम्पस", "Site ya campus"),
    "location-masters.steps.3.label": ("Building", "भवन", "इमारत", "Building"),
    "location-masters.steps.3.caption": ("Tower or block", "टावर या ब्लॉक", "टॉवर किंवा ब्लॉक", "Tower ya block"),
    "location-masters.steps.4.label": ("Floor", "मंज़िल", "मजला", "Floor"),
    "location-masters.steps.4.caption": ("Level boundary", "स्तर सीमा", "स्तर सीमा", "Level ki boundary"),
    "location-masters.steps.5.label": ("Room", "कमरा", "खोली", "Room"),
    "location-masters.steps.5.caption": ("Bay or desk", "बे या डेस्क", "बे किंवा डेस्क", "Bay ya desk"),
    "location-masters.fieldRules.0.name": ("Location code", "लोकेशन कोड", "लोकेशन कोड", "Location code"),
    "location-masters.fieldRules.0.description": (
        "Unique across the tenant. Locked once an asset is tagged to it.",
        "पूरे tenant में अद्वितीय। एक बार कोई asset इससे टैग हो जाने पर यह लॉक हो जाता है।",
        "संपूर्ण tenant मध्ये अद्वितीय. एकदा एखादी asset याला टॅग झाली की ते लॉक होते.",
        "Pure tenant mein unique hota hai. Ek baar koi asset isse tag ho jaaye to ye lock ho jaata hai.",
    ),
    "location-masters.fieldRules.1.name": ("Level", "स्तर", "स्तर", "Level"),
    "location-masters.fieldRules.1.description": (
        "Sets which parents are valid and which fields appear on the form.",
        "यह तय करता है कि कौन से parent मान्य हैं और फ़ॉर्म पर कौन-से फ़ील्ड दिखाई देंगे।",
        "हे ठरवते की कोणते parents वैध आहेत आणि फॉर्मवर कोणती फील्ड्स दिसतील.",
        "Ye decide karta hai ki kaunse parents valid hain aur form par kaunse fields dikhenge.",
    ),
    "location-masters.fieldRules.2.name": ("Parent", "पैरेंट", "पॅरेंट", "Parent"),
    "location-masters.fieldRules.2.description": (
        "Must be exactly one level higher. Blank only for a country.",
        "ठीक एक स्तर ऊपर होना चाहिए। केवल देश (country) के लिए यह खाली रह सकता है।",
        "अगदी एक स्तर वर असणे आवश्यक आहे. फक्त country साठी हे रिकामे राहू शकते.",
        "Exactly ek level upar hona chahiye. Sirf country ke liye ye blank reh sakta hai.",
    ),
    "location-masters.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "location-masters.fieldRules.3.description": (
        "Inactive hides it from selection lists but keeps historical records intact.",
        "Inactive करने पर यह selection lists से छिप जाता है, लेकिन historical records अक्षुण्ण रहते हैं।",
        "Inactive केल्यास ते selection lists मधून लपते, पण historical records जसेच्या तसे राहतात.",
        "Inactive karne par ye selection lists se hide ho jaata hai, lekin historical records intact rehte hain.",
    ),
    "location-masters.tip.title": (
        "Importing in bulk",
        "बल्क में इम्पोर्ट करना",
        "बल्कमध्ये इम्पोर्ट करणे",
        "Bulk mein import karna",
    ),
    "location-masters.tip.body": (
        "Sort the sheet so parent rows appear above their children — the importer validates each row against locations already saved. Failed rows land in Validation Errors with the reason.",
        "शीट को इस तरह सॉर्ट करें कि parent rows अपने children से ऊपर दिखें — importer हर row को पहले से saved locations के विरुद्ध validate करता है। असफल rows कारण सहित Validation Errors में चली जाती हैं।",
        "शीट अशी sort करा की parent rows त्यांच्या children च्या वर दिसतील — importer प्रत्येक row आधीच saved असलेल्या locations विरुद्ध validate करतो. अयशस्वी rows कारणासह Validation Errors मध्ये जातात.",
        "Sheet ko is tarah sort karein ki parent rows apne children ke upar aayein — importer har row ko already-saved locations ke against validate karta hai. Fail hui rows reason ke saath Validation Errors mein chali jaati hain.",
    ),
}


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 LOCATION_MASTERS.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(LOCATION_MASTERS)} location-masters keys.")


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