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

Usage: docker compose exec api python seed_translations_pageinfo_asset_creation_queue.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_CREATION_QUEUE = {
    "asset-creation-queue.title": (
        "Asset Creation Queue",
        "एसेट क्रिएशन क्यू",
        "अॅसेट क्रिएशन क्यू",
        "Asset Creation Queue",
    ),
    "asset-creation-queue.subtitle": (
        "Turn stock receipts into capital assets",
        "स्टॉक रिसीट्स को कैपिटल असेट्स में बदलें",
        "स्टॉक रिसीट्सना कॅपिटल अॅसेट्समध्ये रूपांतरित करा",
        "Stock receipts ko capital assets mein convert karein",
    ),
    "asset-creation-queue.body.0": (
        "This queue is not a separate list — it's every real Inventory stock-in transaction (the same 'goods received' entries as the Goods Receipt Register), joined with the item catalog to show cost, category, and received date.",
        "यह कतार कोई अलग लिस्ट नहीं है — यह हर वास्तविक Inventory stock-in transaction है (Goods Receipt Register की तरह वही 'goods received' entries), जिसे item catalog के साथ जोड़कर cost, category, और received date दिखाई जाती है।",
        "हे queue वेगळी यादी नाही — ही प्रत्येक खरी Inventory stock-in transaction आहे (Goods Receipt Register प्रमाणेच त्याच 'goods received' entries), जी item catalog सोबत जोडून cost, category, आणि received date दाखवते.",
        "Ye queue koi alag list nahi hai — ye har real Inventory stock-in transaction hai (Goods Receipt Register jaisi wahi 'goods received' entries), jo item catalog ke saath join hokar cost, category, aur received date dikhati hai.",
    ),
    "asset-creation-queue.body.1": (
        "Capitalizing a row creates a permanent Asset Register record and tags its description with the source transaction's ID, so that receipt can never be capitalized twice.",
        "किसी row को capitalize करने पर एक स्थायी Asset Register record बनता है और उसके description में source transaction की ID टैग की जाती है, ताकि वह receipt कभी दोबारा capitalize न हो सके।",
        "एखादी row capitalize केल्यास कायमस्वरूपी Asset Register record तयार होते आणि तिच्या description मध्ये source transaction चा ID टॅग केला जातो, जेणेकरून ती receipt पुन्हा कधीही capitalize होऊ शकणार नाही.",
        "Kisi row ko capitalize karne par ek permanent Asset Register record banta hai aur uske description mein source transaction ki ID tag ho jaati hai, taaki wo receipt kabhi dobara capitalize na ho sake.",
    ),
    "asset-creation-queue.stepsHeading": (
        "How a receipt becomes an asset",
        "एक receipt asset कैसे बनता है",
        "एक receipt asset कशी बनते",
        "Ek receipt asset kaise banti hai",
    ),
    "asset-creation-queue.steps.0.label": ("Stock Received", "स्टॉक प्राप्त", "स्टॉक प्राप्त", "Stock Received"),
    "asset-creation-queue.steps.0.caption": (
        "Logged as a stock-in transaction in Inventory",
        "Inventory में stock-in transaction के रूप में दर्ज",
        "Inventory मध्ये stock-in transaction म्हणून नोंदवले जाते",
        "Inventory mein stock-in transaction ke roop mein log hota hai",
    ),
    "asset-creation-queue.steps.1.label": ("Pending", "लंबित", "प्रलंबित", "Pending"),
    "asset-creation-queue.steps.1.caption": (
        "Listed here until it's turned into an asset",
        "जब तक asset में न बदला जाए, यहाँ सूचीबद्ध रहता है",
        "asset मध्ये रूपांतरित होईपर्यंत हे इथे सूचीबद्ध राहते",
        "Jab tak asset mein convert nahi hota, tab tak yahan listed rehta hai",
    ),
    "asset-creation-queue.steps.2.label": ("Capitalize", "Capitalize करें", "Capitalize करा", "Capitalize"),
    "asset-creation-queue.steps.2.caption": (
        "Assign Asset Class, Location, Funding Source, and date",
        "Asset Class, Location, Funding Source, और date असाइन करें",
        "Asset Class, Location, Funding Source, आणि date नियुक्त करा",
        "Asset Class, Location, Funding Source, aur date assign karein",
    ),
    "asset-creation-queue.steps.3.label": ("Capitalized", "Capitalized", "Capitalized", "Capitalized"),
    "asset-creation-queue.steps.3.caption": (
        "A new Asset Register record is created and linked back to the receipt",
        "एक नया Asset Register record बनता है और उसे receipt से वापस लिंक किया जाता है",
        "नवीन Asset Register record तयार होते आणि ते receipt शी परत लिंक केले जाते",
        "Ek naya Asset Register record banta hai aur use receipt se wapas link kiya jaata hai",
    ),
    "asset-creation-queue.fieldRules.0.name": (
        "Target Asset Class",
        "लक्षित Asset Class",
        "लक्ष्य Asset Class",
        "Target Asset Class",
    ),
    "asset-creation-queue.fieldRules.0.description": (
        "Determines how the new asset is categorized and valued going forward.",
        "यह तय करता है कि नए asset को आगे कैसे categorize और value किया जाएगा।",
        "हे ठरवते की नवीन asset पुढे कशी categorize आणि value केली जाईल.",
        "Ye decide karta hai ki naya asset aage kaise categorize aur value kiya jaayega.",
    ),
    "asset-creation-queue.fieldRules.1.name": ("Location", "Location", "Location", "Location"),
    "asset-creation-queue.fieldRules.1.description": (
        "Physical location the created asset will be registered at.",
        "वह physical location जहाँ बनाया गया asset रजिस्टर्ड होगा।",
        "ती physical location जिथे तयार केलेली asset नोंदणीकृत होईल.",
        "Wo physical location jahan create hui asset register hogi.",
    ),
    "asset-creation-queue.fieldRules.2.name": ("Funding Source", "Funding Source", "Funding Source", "Funding Source"),
    "asset-creation-queue.fieldRules.2.description": (
        "Must be an active, approved code from the Funding Source master.",
        "Funding Source master से एक active, approved code होना चाहिए।",
        "Funding Source master मधील active, approved code असणे आवश्यक आहे.",
        "Funding Source master se ek active, approved code hona chahiye.",
    ),
    "asset-creation-queue.fieldRules.3.name": ("Acquisition Date", "Acquisition Date", "Acquisition Date", "Acquisition Date"),
    "asset-creation-queue.fieldRules.3.description": (
        "Pre-filled from the receipt's received date, but editable.",
        "receipt की received date से पहले से भरी होती है, लेकिन इसे बदला जा सकता है।",
        "receipt च्या received date मधून आधीच भरलेली असते, पण ती संपादित करता येते.",
        "Receipt ki received date se pre-filled hoti hai, lekin edit ki jaa sakti hai.",
    ),
    "asset-creation-queue.fieldRules.4.name": (
        "Useful Life Override",
        "Useful Life Override",
        "Useful Life Override",
        "Useful Life Override",
    ),
    "asset-creation-queue.fieldRules.4.description": (
        "Optional positive number, in years; leave blank to use the Asset Class default.",
        "वैकल्पिक positive संख्या, वर्षों में; Asset Class के default का उपयोग करने के लिए इसे खाली छोड़ें।",
        "ऐच्छिक positive संख्या, वर्षांमध्ये; Asset Class च्या default चा वापर करण्यासाठी हे रिकामे सोडा.",
        "Optional positive number, years mein; Asset Class ka default use karne ke liye blank chhod dein.",
    ),
    "asset-creation-queue.tip.title": (
        "Capitalized status is derived, not stored",
        "Capitalized status derive किया जाता है, स्टोर नहीं",
        "Capitalized status derive केला जातो, स्टोर केला जात नाही",
        "Capitalized status derive hota hai, store nahi",
    ),
    "asset-creation-queue.tip.body": (
        "A receipt shows 'Capitalized' only because an asset exists whose description references its transaction ID — there's no flag on the receipt itself. If that asset's description is later edited or cleared, the receipt will reappear here as Pending even though it was already converted.",
        "कोई receipt 'Capitalized' इसलिए दिखती है क्योंकि एक ऐसा asset मौजूद है जिसके description में उसकी transaction ID का reference है — receipt पर खुद कोई flag नहीं होता। अगर बाद में उस asset का description edit या clear कर दिया जाए, तो वह receipt पहले से convert होने के बावजूद यहाँ फिर से Pending के रूप में दिखने लगेगी।",
        "एखादी receipt 'Capitalized' म्हणून दिसते कारण असे एक asset अस्तित्वात असते ज्याच्या description मध्ये तिच्या transaction ID चा संदर्भ असतो — receipt वर स्वतः कोणताही flag नसतो. जर नंतर त्या asset चे description edit किंवा clear केले गेले, तर ती receipt आधीच convert झालेली असूनही इथे पुन्हा Pending म्हणून दिसेल.",
        "Ek receipt 'Capitalized' isliye dikhti hai kyunki ek asset exist karta hai jiske description mein uski transaction ID ka reference hota hai — receipt par khud koi flag nahi hota. Agar baad mein us asset ka description edit ya clear kar diya jaaye, to wo receipt pehle se convert ho chuki hone ke bawajood yahan phir se Pending dikhegi.",
    ),
}


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_CREATION_QUEUE.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_CREATION_QUEUE)} asset-creation-queue keys.")


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