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

Usage: docker compose exec api python seed_translations_pageinfo_financial_masters.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_MASTERS = {
    "financial-masters.title": (
        "Financial Masters",
        "वित्तीय मास्टर",
        "आर्थिक मास्टर",
        "Financial Masters",
    ),
    "financial-masters.subtitle": (
        "Chart of accounts, cost centres and the fiscal period calendar",
        "खातों का चार्ट, कॉस्ट सेंटर और फिस्कल पीरियड कैलेंडर",
        "खात्यांचा चार्ट, कॉस्ट सेंटर आणि फिस्कल पीरियड कॅलेंडर",
        "Chart of accounts, cost centres aur fiscal period calendar",
    ),
    "financial-masters.body.0": (
        "Chart of accounts, cost centres, and fiscal period calendar.",
        "खातों का चार्ट, कॉस्ट सेंटर, और फिस्कल पीरियड कैलेंडर।",
        "खात्यांचा चार्ट, कॉस्ट सेंटर आणि फिस्कल पीरियड कॅलेंडर.",
        "Chart of accounts, cost centres, aur fiscal period calendar.",
    ),
    "financial-masters.body.1": (
        "Accounts and fiscal periods are read-only lookups maintained via GSTN/finance system sync; cost centres can be created here.",
        "Accounts और fiscal periods, GSTN/finance system sync के ज़रिए बनाए रखे जाने वाले read-only lookups हैं; cost centres यहाँ बनाए जा सकते हैं।",
        "Accounts आणि fiscal periods हे GSTN/finance system sync द्वारे राखले जाणारे read-only lookups आहेत; cost centres इथे तयार करता येतात.",
        "Accounts aur fiscal periods GSTN/finance system sync ke through maintain hone wale read-only lookups hain; cost centres yahan create kiye ja sakte hain.",
    ),
    "financial-masters.stepsHeading": (
        "How the three registers flow",
        "तीनों रजिस्टर कैसे मिलकर काम करते हैं",
        "तिन्ही रजिस्टर एकत्र कसे कार्य करतात",
        "Teeno registers kaise flow karte hain",
    ),
    "financial-masters.steps.0.label": ("GSTN Sync", "GSTN Sync", "GSTN Sync", "GSTN Sync"),
    "financial-masters.steps.0.caption": (
        "Sync GSTN pulls the chart of accounts and fiscal period calendar from your finance system.",
        "Sync GSTN आपके finance system से chart of accounts और fiscal period calendar खींचकर लाता है।",
        "Sync GSTN तुमच्या finance system मधून chart of accounts आणि fiscal period calendar आणते.",
        "Sync GSTN aapke finance system se chart of accounts aur fiscal period calendar pull karta hai.",
    ),
    "financial-masters.steps.1.label": ("Chart of Accounts", "Chart of Accounts", "Chart of Accounts", "Chart of Accounts"),
    "financial-masters.steps.1.caption": (
        "Read-only ledger accounts with GL mapping; refreshed only by sync, never created here.",
        "GL mapping सहित read-only ledger accounts; ये केवल sync से refresh होते हैं, यहाँ कभी नहीं बनाए जाते।",
        "GL mapping सह read-only ledger accounts; हे फक्त sync द्वारे refresh होतात, इथे कधीही तयार केले जात नाहीत.",
        "GL mapping ke saath read-only ledger accounts; ye sirf sync se refresh hote hain, yahan kabhi create nahi hote.",
    ),
    "financial-masters.steps.2.label": ("Cost Centres", "Cost Centres", "Cost Centres", "Cost Centres"),
    "financial-masters.steps.2.caption": (
        "The one editable register — add a Code and Name to track spend by department or unit.",
        "यह एकमात्र editable रजिस्टर है — department या unit के अनुसार खर्च ट्रैक करने के लिए Code और Name जोड़ें।",
        "हे एकमेव editable रजिस्टर आहे — department किंवा unit नुसार खर्च ट्रॅक करण्यासाठी Code आणि Name जोडा.",
        "Ye ek hi editable register hai — department ya unit ke hisaab se spend track karne ke liye Code aur Name add karein.",
    ),
    "financial-masters.steps.3.label": ("Used Downstream", "आगे इस्तेमाल होता है", "पुढे वापरले जाते", "Downstream Use Hota Hai"),
    "financial-masters.steps.3.caption": (
        "Cost centres and fiscal periods feed Budget Allocation, PO cost tagging and custody assignment elsewhere in AMS.",
        "Cost centres और fiscal periods, AMS में कहीं और Budget Allocation, PO cost tagging और custody assignment को डेटा देते हैं।",
        "Cost centres आणि fiscal periods, AMS मध्ये इतरत्र Budget Allocation, PO cost tagging आणि custody assignment ला डेटा पुरवतात.",
        "Cost centres aur fiscal periods AMS mein aur jagah Budget Allocation, PO cost tagging aur custody assignment ko feed karte hain.",
    ),
    "financial-masters.fieldRules.0.name": ("Cost Centre Code", "Cost Centre Code", "Cost Centre Code", "Cost Centre Code"),
    "financial-masters.fieldRules.0.description": (
        "Short unique identifier (e.g. CC-IT); Create stays disabled until Code and Name are both filled.",
        "एक छोटा unique identifier (जैसे CC-IT); जब तक Code और Name दोनों नहीं भरे जाते, Create बटन disabled रहता है।",
        "एक लहान unique identifier (उदा. CC-IT); जोपर्यंत Code आणि Name दोन्ही भरले जात नाहीत, तोपर्यंत Create बटण disabled राहते.",
        "Ek short unique identifier (jaise CC-IT); jab tak Code aur Name dono fill nahi hote, Create button disabled rehta hai.",
    ),
    "financial-masters.fieldRules.1.name": ("Cost Centre Name", "Cost Centre Name", "Cost Centre Name", "Cost Centre Name"),
    "financial-masters.fieldRules.1.description": (
        "Display name (e.g. IT Department); shown wherever cost centres are picked, like Budget Allocation.",
        "Display नाम (जैसे IT Department); जहाँ भी cost centres चुने जाते हैं, जैसे Budget Allocation में, वहाँ दिखाया जाता है।",
        "Display नाव (उदा. IT Department); जिथे कुठे cost centres निवडले जातात, जसे Budget Allocation मध्ये, तिथे दाखवले जाते.",
        "Display naam (jaise IT Department); jahan bhi cost centres select kiye jaate hain, jaise Budget Allocation mein, wahan dikhaya jaata hai.",
    ),
    "financial-masters.fieldRules.2.name": ("Account Type / GL Mapping", "Account Type / GL Mapping", "Account Type / GL Mapping", "Account Type / GL Mapping"),
    "financial-masters.fieldRules.2.description": (
        "Read-only classification and general-ledger mapping pulled from GSTN sync — not editable here.",
        "GSTN sync से लाया गया read-only classification और general-ledger mapping — यहाँ editable नहीं है।",
        "GSTN sync मधून आणलेले read-only classification आणि general-ledger mapping — इथे editable नाही.",
        "GSTN sync se aaya hua read-only classification aur general-ledger mapping — yahan editable nahi hai.",
    ),
    "financial-masters.fieldRules.3.name": ("Fiscal Period Status", "Fiscal Period Status", "Fiscal Period Status", "Fiscal Period Status"),
    "financial-masters.fieldRules.3.description": (
        "Open or Closed — controls whether transactions can post to that period; set by the finance system sync.",
        "Open या Closed — यह नियंत्रित करता है कि उस period में transactions post हो सकते हैं या नहीं; यह finance system sync द्वारा सेट किया जाता है।",
        "Open किंवा Closed — हे नियंत्रित करते की त्या period मध्ये transactions post होऊ शकतात की नाही; हे finance system sync द्वारे सेट केले जाते.",
        "Open ya Closed — ye control karta hai ki us period mein transactions post ho sakte hain ya nahi; ye finance system sync se set hota hai.",
    ),
    "financial-masters.tip.title": (
        "Org Unit isn't set on this page",
        "इस पेज पर Org Unit सेट नहीं होता",
        "या पेजवर Org Unit सेट होत नाही",
        "Is page par Org Unit set nahi hota",
    ),
    "financial-masters.tip.body": (
        "The Cost Centres table has an Org Unit column, but the create form only takes Code and Name — new cost centres show \"-\" for Org Unit until it's assigned some other way.",
        "Cost Centres table में एक Org Unit column है, लेकिन create फ़ॉर्म केवल Code और Name लेता है — जब तक इसे किसी और तरीके से assign नहीं किया जाता, नए cost centres का Org Unit \"-\" दिखाता है।",
        "Cost Centres table मध्ये Org Unit हा column आहे, पण create फॉर्म फक्त Code आणि Name घेतो — जोपर्यंत ते इतर कोणत्यातरी मार्गाने assign होत नाही, तोपर्यंत नवीन cost centres साठी Org Unit \"-\" असे दाखवते.",
        "Cost Centres table mein ek Org Unit column hai, lekin create form sirf Code aur Name leta hai — jab tak isse kisi aur tarike se assign nahi kiya jaata, naye cost centres ka Org Unit \"-\" dikhata 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_MASTERS.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_MASTERS)} financial-masters keys.")


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