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

Usage: docker compose exec api python seed_translations_pageinfo_nbv_dashboard.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)
NBV_DASHBOARD = {
    "nbv-dashboard.title": (
        "Net Book Value — PPE Movement",
        "नेट बुक वैल्यू — PPE मूवमेंट",
        "नेट बुक व्हॅल्यू — PPE मूव्हमेंट",
        "Net Book Value — PPE Movement",
    ),
    "nbv-dashboard.subtitle": (
        "Roll-forward of net book value per asset class for a fiscal year",
        "प्रत्येक asset class के लिए एक fiscal year में net book value का roll-forward",
        "प्रत्येक asset class साठी एका fiscal year मध्ये net book value चे roll-forward",
        "Har asset class ke liye ek fiscal year mein net book value ka roll-forward",
    ),
    "nbv-dashboard.body.0": (
        "Opening net book value, additions, disposals, depreciation, and closing value per asset class for a fiscal year.",
        "प्रत्येक asset class के लिए एक fiscal year में opening net book value, additions, disposals, depreciation, और closing value।",
        "प्रत्येक asset class साठी एका fiscal year मध्ये opening net book value, additions, disposals, depreciation आणि closing value.",
        "Har asset class ke liye ek fiscal year mein opening net book value, additions, disposals, depreciation, aur closing value.",
    ),
    "nbv-dashboard.stepsHeading": (
        "How closing NBV is calculated",
        "Closing NBV की गणना कैसे की जाती है",
        "Closing NBV ची गणना कशी केली जाते",
        "Closing NBV kaise calculate hota hai",
    ),
    "nbv-dashboard.steps.0.label": ("Opening NBV", "Opening NBV", "Opening NBV", "Opening NBV"),
    "nbv-dashboard.steps.0.caption": (
        "Carried forward from the prior fiscal year's closing balance",
        "पिछले fiscal year के closing balance से आगे बढ़ाया गया",
        "मागील fiscal year च्या closing balance मधून पुढे आणले",
        "Pichhle fiscal year ke closing balance se carry forward hota hai",
    ),
    "nbv-dashboard.steps.1.label": ("Additions", "Additions", "Additions", "Additions"),
    "nbv-dashboard.steps.1.caption": (
        "Cost of assets capitalized during the year",
        "वर्ष के दौरान capitalize किए गए assets की लागत",
        "वर्षभरात capitalize केलेल्या assets ची किंमत",
        "Year ke dauran capitalize kiye gaye assets ki cost",
    ),
    "nbv-dashboard.steps.2.label": ("Disposals & Depreciation", "Disposals और Depreciation", "Disposals आणि Depreciation", "Disposals & Depreciation"),
    "nbv-dashboard.steps.2.caption": (
        "Reductions from asset disposals and periodic depreciation",
        "asset disposals और periodic depreciation से होने वाली कमी",
        "asset disposals आणि periodic depreciation मुळे होणारी घट",
        "Asset disposals aur periodic depreciation se hone wali reduction",
    ),
    "nbv-dashboard.steps.3.label": ("Revaluations", "Revaluations", "Revaluations", "Revaluations"),
    "nbv-dashboard.steps.3.caption": (
        "Adjustments booked from any revaluation exercise",
        "किसी भी revaluation exercise से बुक किए गए adjustments",
        "कोणत्याही revaluation exercise मधून बुक केलेले adjustments",
        "Kisi bhi revaluation exercise se book kiye gaye adjustments",
    ),
    "nbv-dashboard.steps.4.label": ("Closing NBV", "Closing NBV", "Closing NBV", "Closing NBV"),
    "nbv-dashboard.steps.4.caption": (
        "Opening + additions − disposals − depreciation ± revaluations",
        "Opening + additions − disposals − depreciation ± revaluations",
        "Opening + additions − disposals − depreciation ± revaluations",
        "Opening + additions − disposals − depreciation ± revaluations",
    ),
    "nbv-dashboard.fieldRules.0.name": ("Fiscal Year", "Fiscal Year", "Fiscal Year", "Fiscal Year"),
    "nbv-dashboard.fieldRules.0.description": (
        "Selects the year whose PPE movement is loaded; defaults to the current fiscal year",
        "उस वर्ष का चयन करता है जिसका PPE movement लोड होता है; डिफ़ॉल्ट रूप से current fiscal year होता है",
        "ज्या वर्षाचे PPE movement लोड होते ते वर्ष निवडते; डीफॉल्टनुसार current fiscal year असते",
        "Us year ko select karta hai jiska PPE movement load hota hai; default current fiscal year hota hai",
    ),
    "nbv-dashboard.fieldRules.1.name": ("Opening NBV", "Opening NBV", "Opening NBV", "Opening NBV"),
    "nbv-dashboard.fieldRules.1.description": (
        "The asset class's closing balance from the previous fiscal year",
        "पिछले fiscal year का asset class का closing balance",
        "मागील fiscal year मधील asset class चा closing balance",
        "Asset class ka pichhle fiscal year ka closing balance",
    ),
    "nbv-dashboard.fieldRules.2.name": ("Additions", "Additions", "Additions", "Additions"),
    "nbv-dashboard.fieldRules.2.description": (
        "Value of assets capitalized into this class during the year",
        "वर्ष के दौरान इस class में capitalize किए गए assets का value",
        "वर्षभरात या class मध्ये capitalize केलेल्या assets ची value",
        "Year ke dauran is class mein capitalize kiye gaye assets ki value",
    ),
    "nbv-dashboard.fieldRules.3.name": ("Depreciation", "Depreciation", "Depreciation", "Depreciation"),
    "nbv-dashboard.fieldRules.3.description": (
        "Total depreciation charged against the class for the year",
        "वर्ष के लिए class के विरुद्ध चार्ज किया गया कुल depreciation",
        "वर्षासाठी class च्या विरुद्ध आकारलेले एकूण depreciation",
        "Year ke liye class ke against charge kiya gaya total depreciation",
    ),
    "nbv-dashboard.fieldRules.4.name": ("Closing NBV", "Closing NBV", "Closing NBV", "Closing NBV"),
    "nbv-dashboard.fieldRules.4.description": (
        "Net book value at year end; becomes next year's opening balance",
        "वर्ष के अंत में net book value; यह अगले वर्ष का opening balance बन जाता है",
        "वर्षअखेरीस net book value; हे पुढील वर्षाचा opening balance बनते",
        "Year-end par net book value; ye agle year ka opening balance ban jaata hai",
    ),
    "nbv-dashboard.tip.title": (
        "Cross-check consecutive years",
        "लगातार वर्षों की cross-check करें",
        "सलग वर्षांची cross-check करा",
        "Consecutive years ko cross-check karein",
    ),
    "nbv-dashboard.tip.body": (
        "Closing NBV for a fiscal year should equal Opening NBV for the following year. A mismatch usually means entries were posted after the prior year closed — reload both years before trusting the figures.",
        "एक fiscal year का Closing NBV अगले वर्ष के Opening NBV के बराबर होना चाहिए। mismatch का सामान्यतः मतलब है कि entries पिछले वर्ष के बंद होने के बाद post की गई थीं — figures पर भरोसा करने से पहले दोनों वर्षों को reload करें।",
        "एका fiscal year चा Closing NBV पुढील वर्षाच्या Opening NBV च्या बरोबर असावा. mismatch चा साधारणपणे अर्थ असा होतो की entries मागील वर्ष बंद झाल्यानंतर post केल्या गेल्या — figures वर विश्वास ठेवण्यापूर्वी दोन्ही वर्षे reload करा.",
        "Ek fiscal year ka Closing NBV agle year ke Opening NBV ke barabar hona chahiye. Mismatch ka aam taur par matlab hai ki entries pichhle year close hone ke baad post hui thi — figures par bharosa karne se pehle dono years reload karein.",
    ),
}


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 NBV_DASHBOARD.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(NBV_DASHBOARD)} nbv-dashboard keys.")


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