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

Usage: docker compose exec api python seed_translations_pageinfo_ca_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)
CA_DASHBOARD = {
    "ca-dashboard.title": (
        "CA Financial Dashboard",
        "CA वित्तीय डैशबोर्ड",
        "CA आर्थिक डॅशबोर्ड",
        "CA Financial Dashboard",
    ),
    "ca-dashboard.subtitle": (
        "Read-only financial & compliance view for Chartered Accountants",
        "Chartered Accountants के लिए केवल-पठन (read-only) वित्तीय और अनुपालन दृश्य",
        "Chartered Accountants साठी फक्त-वाचनीय (read-only) आर्थिक आणि अनुपालन दृश्य",
        "Chartered Accountants ke liye read-only financial aur compliance view",
    ),
    "ca-dashboard.body.0": (
        "Asset-wise valuation, depreciation across all 3 statutory books, and compliance readiness — read-only.",
        "Asset-वार वैल्यूएशन, तीनों statutory books में depreciation, और compliance readiness — केवल-पठन (read-only)।",
        "Asset-निहाय valuation, तिन्ही statutory books मधील depreciation, आणि compliance readiness — फक्त-वाचनीय (read-only).",
        "Asset-wise valuation, sabhi 3 statutory books mein depreciation, aur compliance readiness — read-only.",
    ),
    "ca-dashboard.body.1": (
        "This page has no write permissions — it composes the CFO and Auditor dashboard data plus a dedicated asset-wise reconciliation between Companies Act, Income Tax, and Ind AS net book value.",
        "इस पेज पर कोई write permission नहीं है — यह CFO और Auditor डैशबोर्ड डेटा के साथ-साथ Companies Act, Income Tax, और Ind AS net book value के बीच एक समर्पित asset-वार reconciliation प्रस्तुत करता है।",
        "या पेजवर कोणतेही write permission नाही — हे CFO आणि Auditor डॅशबोर्ड डेटा सोबतच Companies Act, Income Tax, आणि Ind AS net book value यांच्यातील एक समर्पित asset-निहाय reconciliation दाखवते.",
        "Is page par koi write permission nahi hai — ye CFO aur Auditor dashboard data ke saath-saath Companies Act, Income Tax, aur Ind AS net book value ke beech ek dedicated asset-wise reconciliation compose karta hai.",
    ),
    "ca-dashboard.stepsHeading": (
        "How the 3-book reconciliation works",
        "3-book reconciliation कैसे काम करता है",
        "3-book reconciliation कसे कार्य करते",
        "3-book reconciliation kaise kaam karta hai",
    ),
    "ca-dashboard.steps.0.label": ("Select Period", "अवधि चुनें", "कालावधी निवडा", "Period Select karein"),
    "ca-dashboard.steps.0.caption": (
        "Pick a month with the date picker above the reconciliation table.",
        "reconciliation table के ऊपर दिए गए date picker से एक महीना चुनें।",
        "reconciliation table च्या वर दिलेल्या date picker मधून एक महिना निवडा.",
        "Reconciliation table ke upar diye gaye date picker se ek month choose karein.",
    ),
    "ca-dashboard.steps.1.label": ("Run", "Run करें", "Run करा", "Run karein"),
    "ca-dashboard.steps.1.caption": (
        "Fetches asset-wise NBV under all three statutory books for that month.",
        "उस महीने के लिए तीनों statutory books के अंतर्गत asset-वार NBV प्राप्त करता है।",
        "त्या महिन्यासाठी तिन्ही statutory books अंतर्गत asset-निहाय NBV आणते.",
        "Us month ke liye teeno statutory books ke under asset-wise NBV fetch karta hai.",
    ),
    "ca-dashboard.steps.2.label": ("Review Differences", "अंतर की समीक्षा करें", "फरकांचे पुनरावलोकन करा", "Differences review karein"),
    "ca-dashboard.steps.2.caption": (
        "Rows marked \"Difference\" have a mismatched NBV across the three books.",
        "जिन rows पर \"Difference\" अंकित है, उनमें तीनों books में NBV मेल नहीं खाता।",
        "ज्या rows वर \"Difference\" असे चिन्हांकित आहे, त्यांच्यात तिन्ही books मध्ये NBV जुळत नाही.",
        "Jin rows par \"Difference\" mark hai, unmein teeno books mein NBV match nahi karta.",
    ),
    "ca-dashboard.steps.3.label": ("Export", "Export करें", "Export करा", "Export karein"),
    "ca-dashboard.steps.3.caption": (
        "Download the table for your audit workpapers.",
        "अपने audit workpapers के लिए table डाउनलोड करें।",
        "तुमच्या audit workpapers साठी table डाउनलोड करा.",
        "Apne audit workpapers ke liye table download karein.",
    ),
    "ca-dashboard.fieldRules.0.name": ("Reconciliation Period", "Reconciliation अवधि", "Reconciliation कालावधी", "Reconciliation Period"),
    "ca-dashboard.fieldRules.0.description": (
        "Month selector for the asset-wise 3-book table — independent from the CFO period dropdown above it.",
        "asset-वार 3-book table के लिए महीना चुनने का विकल्प — यह ऊपर दिए गए CFO period dropdown से स्वतंत्र है।",
        "asset-निहाय 3-book table साठी महिना निवडण्याचा पर्याय — हा वर दिलेल्या CFO period dropdown पासून स्वतंत्र आहे.",
        "Asset-wise 3-book table ke liye month selector — ye upar diye gaye CFO period dropdown se independent hai.",
    ),
    "ca-dashboard.fieldRules.1.name": (
        "Companies Act / Income Tax / Ind AS NBV",
        "Companies Act / Income Tax / Ind AS NBV",
        "Companies Act / Income Tax / Ind AS NBV",
        "Companies Act / Income Tax / Ind AS NBV",
    ),
    "ca-dashboard.fieldRules.1.description": (
        "Net book value under each statutory book for the selected period; a dash means no depreciation entry exists yet.",
        "चयनित अवधि के लिए प्रत्येक statutory book के अंतर्गत net book value; डैश (dash) का मतलब है कि अभी तक कोई depreciation entry मौजूद नहीं है।",
        "निवडलेल्या कालावधीसाठी प्रत्येक statutory book अंतर्गत net book value; डॅश (dash) म्हणजे अद्याप कोणतीही depreciation entry अस्तित्वात नाही.",
        "Selected period ke liye har statutory book ke under net book value; dash ka matlab hai abhi tak koi depreciation entry exist nahi karti.",
    ),
    "ca-dashboard.fieldRules.2.name": ("Status", "स्थिति (Status)", "स्थिती (Status)", "Status"),
    "ca-dashboard.fieldRules.2.description": (
        "\"Difference\" when the three NBVs don't match; \"Reconciled\" when they agree.",
        "जब तीनों NBV मेल नहीं खाते तो \"Difference\", और जब वे मेल खाते हैं तो \"Reconciled\" दिखाया जाता है।",
        "जेव्हा तिन्ही NBV जुळत नाहीत तेव्हा \"Difference\", आणि जेव्हा ते जुळतात तेव्हा \"Reconciled\" दाखवले जाते.",
        "Jab teeno NBV match nahi karte to \"Difference\", aur jab wo match karte hain to \"Reconciled\" dikhta hai.",
    ),
    "ca-dashboard.fieldRules.3.name": ("CFO Period (top dropdown)", "CFO अवधि (ऊपर का dropdown)", "CFO कालावधी (वरील dropdown)", "CFO Period (top dropdown)"),
    "ca-dashboard.fieldRules.3.description": (
        "Controls only the six KPI cards and the NBV-by-asset-class table, not the reconciliation section below.",
        "यह केवल छह KPI cards और NBV-by-asset-class table को नियंत्रित करता है, नीचे दिए गए reconciliation सेक्शन को नहीं।",
        "हे फक्त सहा KPI cards आणि NBV-by-asset-class table नियंत्रित करते, खाली दिलेल्या reconciliation सेक्शनला नाही.",
        "Ye sirf six KPI cards aur NBV-by-asset-class table ko control karta hai, neeche wale reconciliation section ko nahi.",
    ),
    "ca-dashboard.tip.title": (
        "Two independent period filters",
        "दो स्वतंत्र अवधि फ़िल्टर",
        "दोन स्वतंत्र कालावधी फिल्टर्स",
        "Do independent period filters",
    ),
    "ca-dashboard.tip.body": (
        "The top-right period dropdown only refreshes the KPI cards and NBV-by-class table. The asset-wise 3-book reconciliation has its own month picker and Run button — changing one does not refresh the other.",
        "ऊपर-दाईं ओर का period dropdown केवल KPI cards और NBV-by-class table को refresh करता है। asset-वार 3-book reconciliation का अपना अलग month picker और Run बटन है — एक को बदलने से दूसरा refresh नहीं होता।",
        "वर-उजवीकडील period dropdown फक्त KPI cards आणि NBV-by-class table refresh करते. asset-निहाय 3-book reconciliation ला स्वतःचा वेगळा month picker आणि Run बटण आहे — एक बदलल्याने दुसरे refresh होत नाही.",
        "Top-right wala period dropdown sirf KPI cards aur NBV-by-class table ko refresh karta hai. Asset-wise 3-book reconciliation ka apna alag month picker aur Run button hai — ek ko change karne se dusra refresh nahi hota.",
    ),
}


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 CA_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(CA_DASHBOARD)} ca-dashboard keys.")


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