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

Usage: docker compose exec api python seed_translations_pageinfo_depreciation_master.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)
DEPRECIATION_MASTER = {
    "depreciation-master.title": (
        "Depreciation Master",
        "डेप्रिसिएशन मास्टर",
        "डेप्रिसिएशन मास्टर",
        "Depreciation Master",
    ),
    "depreciation-master.subtitle": (
        "The rate table the Depreciation Run reads from",
        "वह रेट टेबल जिसे Depreciation Run पढ़ता है",
        "ती रेट टेबल जी Depreciation Run वाचते",
        "Wo rate table jise Depreciation Run read karta hai",
    ),
    "depreciation-master.body.0": (
        "Government-mandated depreciation rates per asset class, book, and fiscal year.",
        "प्रति asset class, book और fiscal year सरकार द्वारा निर्धारित depreciation दरें।",
        "प्रत्येक asset class, book आणि fiscal year साठी सरकारने निर्धारित केलेले depreciation दर.",
        "Har asset class, book, aur fiscal year ke liye government-mandated depreciation rates.",
    ),
    "depreciation-master.body.1": (
        "Each row defines the rate, method and useful life for one Fiscal Year + Asset Class + Book combination. When Finance runs periodic depreciation, it looks up the matching row here to calculate the charge for every asset in that class.",
        "हर row एक Fiscal Year + Asset Class + Book combination के लिए rate, method और useful life तय करती है। जब Finance periodic depreciation run करता है, तो वह उस class के हर asset के लिए charge calculate करने के लिए यहाँ matching row देखता है।",
        "प्रत्येक row एका Fiscal Year + Asset Class + Book combination साठी rate, method आणि useful life ठरवते. जेव्हा Finance periodic depreciation run करते, तेव्हा त्या class मधील प्रत्येक asset साठी charge calculate करण्यासाठी ते इथे matching row पाहते.",
        "Har row ek Fiscal Year + Asset Class + Book combination ke liye rate, method aur useful life define karti hai. Jab Finance periodic depreciation run karta hai, tab wo us class ke har asset ke liye charge calculate karne ke liye yahan matching row dekhta hai.",
    ),
    "depreciation-master.stepsHeading": (
        "How a rate is scoped",
        "एक rate का scope कैसे तय होता है",
        "एका rate चा scope कसा ठरतो",
        "Ek rate ka scope kaise decide hota hai",
    ),
    "depreciation-master.steps.0.label": ("Fiscal Year", "वित्तीय वर्ष", "आर्थिक वर्ष", "Fiscal Year"),
    "depreciation-master.steps.0.caption": (
        "Which year this rate set applies to.",
        "यह rate set किस वर्ष पर लागू होता है।",
        "हा rate set कोणत्या वर्षासाठी लागू होतो.",
        "Ye rate set kis year ke liye applicable hai.",
    ),
    "depreciation-master.steps.1.label": ("Asset Class", "एसेट क्लास", "असेट क्लास", "Asset Class"),
    "depreciation-master.steps.1.caption": (
        "The asset category the rate covers, e.g. IT Equipment.",
        "asset की वह category जिस पर यह rate लागू होता है, जैसे IT Equipment।",
        "ज्या asset category साठी हा rate लागू होतो, उदा. IT Equipment.",
        "Wo asset category jispe ye rate apply hota hai, jaise IT Equipment.",
    ),
    "depreciation-master.steps.2.label": ("Book", "बुक", "बुक", "Book"),
    "depreciation-master.steps.2.caption": (
        "Companies Act, Income Tax, or Ind AS — each can carry a different rate.",
        "Companies Act, Income Tax, या Ind AS — हर एक की rate अलग हो सकती है।",
        "Companies Act, Income Tax, किंवा Ind AS — प्रत्येकाचा rate वेगळा असू शकतो.",
        "Companies Act, Income Tax, ya Ind AS — har ek ka rate alag ho sakta hai.",
    ),
    "depreciation-master.steps.3.label": ("Method", "पद्धति", "पद्धत", "Method"),
    "depreciation-master.steps.3.caption": (
        "SLM or WDV — how the depreciation run calculates the charge.",
        "SLM या WDV — depreciation run charge की calculation कैसे करता है।",
        "SLM किंवा WDV — depreciation run charge ची calculation कशी करते.",
        "SLM ya WDV — depreciation run charge kaise calculate karta hai.",
    ),
    "depreciation-master.fieldRules.0.name": ("Fiscal Year", "वित्तीय वर्ष", "आर्थिक वर्ष", "Fiscal Year"),
    "depreciation-master.fieldRules.0.description": (
        "Year this rate applies to; also filters the table and scopes the Run Depreciation control.",
        "वह वर्ष जिस पर यह rate लागू है; यह table को filter भी करता है और Run Depreciation control का scope तय करता है।",
        "हा rate ज्या वर्षासाठी लागू आहे; हे table देखील filter करते आणि Run Depreciation control चा scope ठरवते.",
        "Wo year jispe ye rate applicable hai; ye table ko filter bhi karta hai aur Run Depreciation control ka scope decide karta hai.",
    ),
    "depreciation-master.fieldRules.1.name": ("Asset Class", "एसेट क्लास", "असेट क्लास", "Asset Class"),
    "depreciation-master.fieldRules.1.description": (
        "Asset category from the Asset Class master this rate applies to.",
        "Asset Class master की वह asset category जिस पर यह rate लागू होता है।",
        "Asset Class master मधील ती asset category ज्यावर हा rate लागू होतो.",
        "Asset Class master ki wo asset category jispe ye rate apply hota hai.",
    ),
    "depreciation-master.fieldRules.2.name": ("Book", "बुक", "बुक", "Book"),
    "depreciation-master.fieldRules.2.description": (
        "Regulatory book this rate satisfies — Companies Act, Income Tax, or Ind AS.",
        "वह regulatory book जिसे यह rate satisfy करता है — Companies Act, Income Tax, या Ind AS।",
        "ते regulatory book जे हा rate satisfy करतो — Companies Act, Income Tax, किंवा Ind AS.",
        "Wo regulatory book jise ye rate satisfy karta hai — Companies Act, Income Tax, ya Ind AS.",
    ),
    "depreciation-master.fieldRules.3.name": ("Method", "पद्धति", "पद्धत", "Method"),
    "depreciation-master.fieldRules.3.description": (
        "SLM (Straight Line) or WDV (Written Down Value) calculation basis.",
        "SLM (Straight Line) या WDV (Written Down Value) calculation basis।",
        "SLM (Straight Line) किंवा WDV (Written Down Value) calculation basis.",
        "SLM (Straight Line) ya WDV (Written Down Value) calculation basis.",
    ),
    "depreciation-master.fieldRules.4.name": ("Rate", "रेट", "रेट", "Rate"),
    "depreciation-master.fieldRules.4.description": (
        "Depreciation rate percentage; optional — leave blank to derive it from Useful Life (yrs) instead.",
        "Depreciation rate percentage; optional — इसे खाली छोड़ने पर Useful Life (yrs) से derive किया जाएगा।",
        "Depreciation rate percentage; optional — रिकामे ठेवल्यास ते Useful Life (yrs) वरून derive केले जाईल.",
        "Depreciation rate percentage; optional hai — blank chhod dein to ye Useful Life (yrs) se derive ho jaayega.",
    ),
    "depreciation-master.tip.title": (
        "Deactivate, don't delete",
        "Deactivate करें, delete नहीं",
        "Deactivate करा, delete करू नका",
        "Deactivate karo, delete mat karo",
    ),
    "depreciation-master.tip.body": (
        "Deactivating a rate is reversible (Reactivate undoes it) and never touches past depreciation runs. But a depreciation run only uses rates that exist for that exact Fiscal Year + Asset Class + Book — if a combination is missing or deactivated, that asset class is silently skipped for the run instead of erroring.",
        "किसी rate को deactivate करना reversible है (Reactivate इसे undo कर देता है) और यह past depreciation runs को कभी प्रभावित नहीं करता। लेकिन कोई depreciation run केवल उन्हीं rates का उपयोग करता है जो उस exact Fiscal Year + Asset Class + Book के लिए मौजूद हों — अगर कोई combination missing या deactivated है, तो error देने के बजाय उस run के लिए वह asset class चुपचाप skip हो जाती है।",
        "एखादा rate deactivate करणे reversible आहे (Reactivate ते undo करते) आणि ते past depreciation runs ला कधीही प्रभावित करत नाही. पण एखादा depreciation run फक्त त्या exact Fiscal Year + Asset Class + Book साठी अस्तित्वात असलेले rates वापरतो — जर एखादे combination missing किंवा deactivated असेल, तर error देण्याऐवजी ती asset class त्या run साठी silently skip केली जाते.",
        "Ek rate ko deactivate karna reversible hai (Reactivate ise undo kar deta hai) aur ye past depreciation runs ko kabhi touch nahi karta. Lekin depreciation run sirf un rates ko use karta hai jo us exact Fiscal Year + Asset Class + Book ke liye exist karte hain — agar koi combination missing ya deactivated hai, to error dene ke bajaye wo asset class us run ke liye silently skip ho jaati 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 DEPRECIATION_MASTER.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(DEPRECIATION_MASTER)} depreciation-master keys.")


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