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

Usage: docker compose exec api python seed_translations_pageinfo_custody_temp_assignments.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)
CUSTODY_TEMP_ASSIGNMENTS = {
    "custody-temp-assignments.title": (
        "Temporary Custody Assignments",
        "अस्थायी कस्टडी असाइनमेंट",
        "तात्पुरती कस्टडी असाइनमेंट",
        "Temporary Custody Assignments",
    ),
    "custody-temp-assignments.subtitle": (
        "Short-term custody that expires automatically — no acceptance step.",
        "अल्पकालिक कस्टडी जो स्वतः समाप्त हो जाती है — इसमें स्वीकृति (acceptance) चरण नहीं होता।",
        "अल्पकालीन कस्टडी जी आपोआप संपते — यामध्ये acceptance पायरी नसते.",
        "Short-term custody jo automatically expire ho jaati hai — isme koi acceptance step nahi hota.",
    ),
    "custody-temp-assignments.body.0": (
        "Assign short-term custody with an automatic expiry date.",
        "स्वतः समाप्त होने वाली expiry date के साथ अल्पकालिक कस्टडी असाइन करें।",
        "आपोआप संपणाऱ्या expiry date सह अल्पकालीन कस्टडी असाइन करा.",
        "Ek automatic expiry date ke saath short-term custody assign karein.",
    ),
    "custody-temp-assignments.body.1": (
        "Unlike a regular custody assignment, this takes effect immediately and does not wait for the custodian to accept it. Select an asset on the left to see its history of temporary assignments on the right.",
        "एक सामान्य custody assignment के विपरीत, यह तुरंत प्रभावी हो जाता है और custodian द्वारा स्वीकार किए जाने की प्रतीक्षा नहीं करता। बाईं ओर कोई asset चुनें ताकि दाईं ओर उसके temporary assignments का इतिहास देखा जा सके।",
        "सामान्य custody assignment च्या विपरीत, हे लगेच प्रभावी होते आणि custodian ने स्वीकारण्याची वाट पाहत नाही. डावीकडे एखादी asset निवडा म्हणजे उजवीकडे तिच्या temporary assignments चा इतिहास दिसेल.",
        "Ek regular custody assignment ke unlike, ye turant effective ho jaata hai aur custodian ke accept karne ka wait nahi karta. Left side par ek asset select karein taaki right side par uske temporary assignments ki history dikhe.",
    ),
    "custody-temp-assignments.stepsHeading": (
        "Assignment lifecycle",
        "असाइनमेंट लाइफसाइकिल",
        "असाइनमेंट लाइफसायकल",
        "Assignment lifecycle",
    ),
    "custody-temp-assignments.steps.0.label": ("Active", "सक्रिय", "सक्रिय", "Active"),
    "custody-temp-assignments.steps.0.caption": (
        "Created with an asset, custodian, and expiry date; effective right away.",
        "एक asset, custodian और expiry date के साथ बनाया जाता है; तुरंत प्रभावी होता है।",
        "एखादी asset, custodian आणि expiry date सह तयार केले जाते; लगेच प्रभावी होते.",
        "Ek asset, custodian, aur expiry date ke saath create hota hai; turant effective ho jaata hai.",
    ),
    "custody-temp-assignments.steps.1.label": ("Expired", "समाप्त", "संपलेले", "Expired"),
    "custody-temp-assignments.steps.1.caption": (
        "Expiry date passes with no manual action — the assignment lapses on its own.",
        "बिना किसी मैनुअल कार्रवाई के expiry date बीत जाती है — assignment अपने आप समाप्त हो जाता है।",
        "कोणतीही मॅन्युअल कृती न करता expiry date निघून जाते — असाइनमेंट आपोआप संपते.",
        "Koi manual action liye bina expiry date nikal jaati hai — assignment apne aap lapse ho jaata hai.",
    ),
    "custody-temp-assignments.steps.2.label": ("Reverted", "पूर्ववत", "पूर्ववत", "Reverted"),
    "custody-temp-assignments.steps.2.caption": (
        "Ended early by an admin before the expiry date is reached.",
        "expiry date आने से पहले किसी admin द्वारा समय से पहले समाप्त कर दिया जाता है।",
        "expiry date येण्यापूर्वी एखाद्या admin कडून लवकर संपवले जाते.",
        "Expiry date aane se pehle kisi admin dwara jaldi end kar diya jaata hai.",
    ),
    "custody-temp-assignments.fieldRules.0.name": ("Asset", "एसेट", "एसेट", "Asset"),
    "custody-temp-assignments.fieldRules.0.description": (
        "The asset being temporarily assigned; only one active temp assignment per asset is allowed.",
        "वह asset जिसे अस्थायी रूप से असाइन किया जा रहा है; प्रति asset केवल एक सक्रिय temp assignment की अनुमति है।",
        "जी asset तात्पुरती असाइन केली जात आहे; प्रति asset फक्त एक सक्रिय temp assignment ला परवानगी आहे.",
        "Wo asset jo temporarily assign ki ja rahi hai; per asset sirf ek active temp assignment allowed hai.",
    ),
    "custody-temp-assignments.fieldRules.1.name": ("Custodian", "कस्टोडियन", "कस्टोडियन", "Custodian"),
    "custody-temp-assignments.fieldRules.1.description": (
        "The user who will hold the asset for the duration.",
        "वह user जो इस अवधि के लिए asset अपने पास रखेगा।",
        "जो user या कालावधीसाठी asset स्वतःकडे ठेवेल.",
        "Wo user jo is duration ke liye asset apne paas rakhega.",
    ),
    "custody-temp-assignments.fieldRules.2.name": (
        "Expires At",
        "समाप्ति तिथि (Expires At)",
        "समाप्ती तारीख (Expires At)",
        "Expires At",
    ),
    "custody-temp-assignments.fieldRules.2.description": (
        "Date the assignment automatically lapses; must be in the future.",
        "वह तिथि जिस पर assignment स्वतः समाप्त हो जाता है; यह भविष्य की तिथि होनी चाहिए।",
        "ती तारीख ज्यावर असाइनमेंट आपोआप संपते; ती भविष्यातील असणे आवश्यक आहे.",
        "Wo date jis par assignment automatically lapse ho jaata hai; ye future mein honi chahiye.",
    ),
    "custody-temp-assignments.tip.title": (
        "Conflicting assignment",
        "टकराव वाला असाइनमेंट",
        "परस्परविरोधी असाइनमेंट",
        "Conflicting assignment",
    ),
    "custody-temp-assignments.tip.body": (
        "An asset can only have one active temporary assignment at a time. If creation fails, check the table on the right — a prior assignment for that asset is likely still active and needs to expire or be reverted first.",
        "किसी asset का एक समय में केवल एक ही सक्रिय temporary assignment हो सकता है। यदि creation विफल होता है, तो दाईं ओर की table जाँचें — उस asset का पहले का assignment संभवतः अभी भी सक्रिय है और उसे पहले समाप्त होना या पूर्ववत (revert) किया जाना ज़रूरी है।",
        "एका वेळी एका asset चे फक्त एकच सक्रिय temporary assignment असू शकते. जर creation अयशस्वी झाले, तर उजवीकडील table तपासा — त्या asset साठीचे आधीचे assignment बहुधा अजूनही सक्रिय आहे आणि ते आधी संपणे किंवा revert होणे आवश्यक आहे.",
        "Ek asset ka ek time par sirf ek hi active temporary assignment ho sakta hai. Agar creation fail hoti hai, to right side ki table check karein — us asset ka pehla assignment shayad abhi bhi active hai aur usse pehle expire ya revert karna zaroori 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 CUSTODY_TEMP_ASSIGNMENTS.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(CUSTODY_TEMP_ASSIGNMENTS)} custody-temp-assignments keys.")


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