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

Usage: docker compose exec api python seed_translations_pageinfo_financial_reconciliation.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)
FINANCIAL_RECONCILIATION = {
    "financial-reconciliation.title": (
        "Depreciation Book Reconciliation",
        "डेप्रिसिएशन बुक रिकंसिलिएशन",
        "डेप्रिसिएशन बुक रिकन्सिलिएशन",
        "Depreciation Book Reconciliation",
    ),
    "financial-reconciliation.subtitle": (
        "Compare closing NBV and depreciation across Companies Act, Income Tax, and Ind AS books.",
        "Companies Act, Income Tax, और Ind AS बुक्स में क्लोजिंग NBV और डेप्रिसिएशन की तुलना करें।",
        "Companies Act, Income Tax, आणि Ind AS बुक्समधील क्लोजिंग NBV आणि डेप्रिसिएशनची तुलना करा.",
        "Companies Act, Income Tax, aur Ind AS books mein closing NBV aur depreciation compare karein.",
    ),
    "financial-reconciliation.body.0": (
        "Compare closing net book value and depreciation across Companies Act, Income Tax, and Ind AS books.",
        "Companies Act, Income Tax, और Ind AS बुक्स में क्लोजिंग नेट बुक वैल्यू और डेप्रिसिएशन की तुलना करें।",
        "Companies Act, Income Tax, आणि Ind AS बुक्समधील क्लोजिंग नेट बुक व्हॅल्यू आणि डेप्रिसिएशनची तुलना करा.",
        "Companies Act, Income Tax, aur Ind AS books mein closing net book value aur depreciation compare karein.",
    ),
    "financial-reconciliation.body.1": (
        "Each asset is depreciated in parallel under all three books using different methods, so an asset can legitimately have three different closing NBVs for the same period.",
        "हर asset को तीनों बुक्स के तहत अलग-अलग तरीकों का उपयोग करके समानांतर रूप से डेप्रिसिएट किया जाता है, इसलिए एक ही अवधि के लिए asset की तीन अलग-अलग क्लोजिंग NBV होना पूरी तरह सामान्य है।",
        "प्रत्येक asset तिन्ही बुक्समध्ये वेगवेगळ्या पद्धती वापरून समांतरपणे डेप्रिसिएट केली जाते, त्यामुळे एकाच कालावधीसाठी asset ला तीन वेगवेगळ्या क्लोजिंग NBV असणे रास्त आहे.",
        "Har asset teeno books ke under alag-alag methods use karke parallel mein depreciate hoti hai, isliye ek hi period ke liye asset ki teen alag closing NBVs hona bilkul normal hai.",
    ),
    "financial-reconciliation.stepsHeading": (
        "How reconciliation works",
        "रिकंसिलिएशन कैसे काम करता है",
        "रिकन्सिलिएशन कसे कार्य करते",
        "Reconciliation kaise kaam karta hai",
    ),
    "financial-reconciliation.steps.0.label": (
        "Select Period",
        "Period चुनें",
        "Period निवडा",
        "Period select karein",
    ),
    "financial-reconciliation.steps.0.caption": (
        "Pick the fiscal month to reconcile.",
        "रिकंसाइल करने के लिए fiscal month चुनें।",
        "रिकन्साइल करण्यासाठी fiscal month निवडा.",
        "Reconcile karne ke liye fiscal month pick karein.",
    ),
    "financial-reconciliation.steps.1.label": (
        "Run Reconciliation",
        "रिकंसिलिएशन चलाएं",
        "रिकन्सिलिएशन चालवा",
        "Reconciliation run karein",
    ),
    "financial-reconciliation.steps.1.caption": (
        "Pulls closing NBV and depreciation per book for that period.",
        "उस अवधि के लिए प्रत्येक बुक की क्लोजिंग NBV और डेप्रिसिएशन खींचता है।",
        "त्या कालावधीसाठी प्रत्येक बुकची क्लोजिंग NBV आणि डेप्रिसिएशन आणते.",
        "Us period ke liye har book ki closing NBV aur depreciation pull karta hai.",
    ),
    "financial-reconciliation.steps.2.label": (
        "Review Differences",
        "अंतर की समीक्षा करें",
        "फरक तपासा",
        "Differences review karein",
    ),
    "financial-reconciliation.steps.2.caption": (
        "Rows are flagged where the books' NBVs don't match.",
        "जहां बुक्स की NBV मेल नहीं खातीं, वहां rows को फ़्लैग किया जाता है।",
        "जिथे बुक्सच्या NBV जुळत नाहीत तिथे rows फ्लॅग केल्या जातात.",
        "Jahan books ki NBVs match nahi karti, wahan rows flag ho jaati hain.",
    ),
    "financial-reconciliation.steps.3.label": (
        "Trace Source Book",
        "सोर्स बुक ट्रेस करें",
        "सोर्स बुक ट्रेस करा",
        "Source book trace karein",
    ),
    "financial-reconciliation.steps.3.caption": (
        "Investigate the differing entry in the Depreciation Run Wizard.",
        "Depreciation Run Wizard में भिन्न entry की जांच करें।",
        "Depreciation Run Wizard मध्ये वेगळी असलेली entry तपासा.",
        "Depreciation Run Wizard mein differing entry investigate karein.",
    ),
    "financial-reconciliation.fieldRules.0.name": (
        "Period",
        "Period",
        "Period",
        "Period",
    ),
    "financial-reconciliation.fieldRules.0.description": (
        "Month picker; the report covers only this single period, not a range.",
        "Month picker; रिपोर्ट केवल इसी एक अवधि को कवर करती है, किसी range को नहीं।",
        "Month picker; रिपोर्ट फक्त याच एका कालावधीचा समावेश करते, कोणत्याही range चा नाही.",
        "Month picker; report sirf isi single period ko cover karti hai, kisi range ko nahi.",
    ),
    "financial-reconciliation.fieldRules.1.name": (
        "Companies Act NBV",
        "Companies Act NBV",
        "Companies Act NBV",
        "Companies Act NBV",
    ),
    "financial-reconciliation.fieldRules.1.description": (
        "Closing net book value under Schedule II rates (SLM or WDV).",
        "Schedule II दरों (SLM या WDV) के तहत क्लोजिंग नेट बुक वैल्यू।",
        "Schedule II दरांनुसार (SLM किंवा WDV) क्लोजिंग नेट बुक व्हॅल्यू.",
        "Schedule II rates (SLM ya WDV) ke under closing net book value.",
    ),
    "financial-reconciliation.fieldRules.2.name": (
        "Income Tax NBV",
        "Income Tax NBV",
        "Income Tax NBV",
        "Income Tax NBV",
    ),
    "financial-reconciliation.fieldRules.2.description": (
        "Closing NBV under IT Act Section 32 WDV blocks with the half-year convention.",
        "Half-year convention के साथ IT Act Section 32 WDV ब्लॉक्स के तहत क्लोजिंग NBV।",
        "Half-year convention सह IT Act Section 32 WDV ब्लॉक्सनुसार क्लोजिंग NBV.",
        "Half-year convention ke saath IT Act Section 32 WDV blocks ke under closing NBV.",
    ),
    "financial-reconciliation.fieldRules.3.name": (
        "Ind AS NBV",
        "Ind AS NBV",
        "Ind AS NBV",
        "Ind AS NBV",
    ),
    "financial-reconciliation.fieldRules.3.description": (
        "Closing NBV under Ind AS 16 straight-line depreciation with residual value.",
        "Residual value के साथ Ind AS 16 स्ट्रेट-लाइन डेप्रिसिएशन के तहत क्लोजिंग NBV।",
        "Residual value सह Ind AS 16 स्ट्रेट-लाइन डेप्रिसिएशननुसार क्लोजिंग NBV.",
        "Residual value ke saath Ind AS 16 straight-line depreciation ke under closing NBV.",
    ),
    "financial-reconciliation.fieldRules.4.name": (
        "Status",
        "Status",
        "Status",
        "Status",
    ),
    "financial-reconciliation.fieldRules.4.description": (
        "\"Difference\" fires whenever the non-blank NBVs across the three books aren't identical.",
        "जब भी तीनों बुक्स की non-blank NBVs समान न हों, तब \"Difference\" ट्रिगर होता है।",
        "जेव्हा तिन्ही बुक्समधील non-blank NBVs सारख्या नसतात, तेव्हा \"Difference\" ट्रिगर होते.",
        "Jab bhi teeno books ki non-blank NBVs identical nahi hoti, tab \"Difference\" fire hota hai.",
    ),
    "financial-reconciliation.tip.title": (
        "A \"Difference\" is normal, not an error",
        "\"Difference\" होना सामान्य है, कोई error नहीं",
        "\"Difference\" असणे सामान्य आहे, error नाही",
        "\"Difference\" hona normal hai, error nahi",
    ),
    "financial-reconciliation.tip.body": (
        "Because Companies Act, Income Tax, and Ind AS use different depreciation methods, almost every asset will show a book difference — that's expected. Focus instead on assets missing an entry in one book (shown as —), which usually means that book's depreciation run hasn't been executed for the period yet.",
        "चूंकि Companies Act, Income Tax, और Ind AS अलग-अलग डेप्रिसिएशन तरीकों का उपयोग करते हैं, इसलिए लगभग हर asset में book difference दिखेगा — यह अपेक्षित है। इसके बजाय उन assets पर ध्यान दें जिनमें किसी एक बुक की entry गायब है (— के रूप में दिखाई गई), जिसका आमतौर पर मतलब है कि उस बुक का डेप्रिसिएशन run उस अवधि के लिए अभी तक execute नहीं हुआ है।",
        "Companies Act, Income Tax, आणि Ind AS वेगवेगळ्या डेप्रिसिएशन पद्धती वापरत असल्यामुळे, जवळजवळ प्रत्येक asset मध्ये book difference दिसेल — हे अपेक्षित आहे. त्याऐवजी अशा assets कडे लक्ष द्या ज्यांच्यात एका बुकची entry गहाळ आहे (— असे दाखवलेली), ज्याचा सहसा अर्थ असा होतो की त्या बुकचा डेप्रिसिएशन run त्या कालावधीसाठी अजून execute झालेला नाही.",
        "Kyunki Companies Act, Income Tax, aur Ind AS alag-alag depreciation methods use karte hain, isliye almost har asset mein book difference dikhega — ye expected hai. Uske bajaay un assets par focus karein jinme kisi ek book ki entry missing hai (— ke roop mein dikhayi gayi), jiska usually matlab hai ki us book ka depreciation run us period ke liye abhi tak execute nahi hua 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 FINANCIAL_RECONCILIATION.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(FINANCIAL_RECONCILIATION)} financial-reconciliation keys.")


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