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

Usage: docker compose exec api python seed_translations_pageinfo_budget_allocation_report.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)
BUDGET_ALLOCATION_REPORT = {
    "budget-allocation-report.title": (
        "Budget Allocation Report",
        "बजट आवंटन रिपोर्ट",
        "बजेट वाटप अहवाल",
        "Budget Allocation Report",
    ),
    "budget-allocation-report.subtitle": (
        "Approved vs spent vs available per budget line, with the POs and assets funded by each.",
        "प्रत्येक budget line के लिए approved बनाम खर्च (spent) बनाम उपलब्ध (available) राशि, साथ ही हर लाइन से funded POs और assets।",
        "प्रत्येक budget line साठी approved विरुद्ध खर्च (spent) विरुद्ध उपलब्ध (available) रक्कम, तसेच प्रत्येक line ने funded केलेले POs आणि assets.",
        "Har budget line ke liye approved vs spent vs available amount, saath hi har line se funded POs aur assets.",
    ),
    "budget-allocation-report.body.0": (
        "Budget lines by fiscal year with how many purchase orders and assets each funds, plus a drill-down to those records.",
        "fiscal year के अनुसार budget lines, प्रत्येक द्वारा funded purchase orders और assets की संख्या के साथ, और उन records तक drill-down करने की सुविधा।",
        "fiscal year नुसार budget lines, प्रत्येकाने funded केलेल्या purchase orders आणि assets च्या संख्येसह, तसेच त्या records पर्यंत drill-down करण्याची सुविधा.",
        "Fiscal year ke hisaab se budget lines, har ek ne kitne purchase orders aur assets fund kiye hain uske saath, plus un records tak drill-down karne ki facility.",
    ),
    "budget-allocation-report.body.1": (
        "Each row compares the approved amount against actual spend to derive what's still available — the summary tiles above the table total these across every line in the current filter.",
        "हर row, approved राशि की तुलना actual खर्च से करके यह निकालती है कि अभी कितना उपलब्ध है — table के ऊपर मौजूद summary tiles current filter की सभी lines में इन्हें जोड़कर कुल दिखाते हैं।",
        "प्रत्येक row, approved रक्कमेची तुलना actual खर्चाशी करून अजून किती उपलब्ध आहे हे काढते — table वरील summary tiles सध्याच्या filter मधील सर्व lines मधील ही मूल्ये एकत्र करून एकूण दाखवतात.",
        "Har row approved amount ko actual spend se compare karke ye nikaalti hai ki abhi kitna available hai — table ke upar wale summary tiles current filter ki saari lines mein ye sab total karke dikhate hain.",
    ),
    "budget-allocation-report.stepsHeading": (
        "How to read this report",
        "इस रिपोर्ट को कैसे पढ़ें",
        "हा अहवाल कसा वाचावा",
        "Ye report kaise padhein",
    ),
    "budget-allocation-report.steps.0.label": (
        "Select Fiscal Year", "Fiscal Year चुनें", "Fiscal Year निवडा", "Fiscal Year select karein",
    ),
    "budget-allocation-report.steps.0.caption": (
        "Leave blank to combine all years.",
        "सभी वर्षों को मिलाने के लिए इसे खाली छोड़ दें।",
        "सर्व वर्षे एकत्र करण्यासाठी हे रिकामे ठेवा.",
        "Sabhi years ko combine karne ke liye ise blank chhod dein.",
    ),
    "budget-allocation-report.steps.1.label": (
        "Run Report", "Report चलाएं", "Report चालवा", "Report run karein",
    ),
    "budget-allocation-report.steps.1.caption": (
        "Loads budget lines with approved / spent / available totals.",
        "approved / spent / available totals के साथ budget lines लोड करता है।",
        "approved / spent / available totals सह budget lines लोड करते.",
        "Approved / spent / available totals ke saath budget lines load karta hai.",
    ),
    "budget-allocation-report.steps.2.label": (
        "Review Summary Tiles", "Summary Tiles की समीक्षा करें", "Summary Tiles चे पुनरावलोकन करा", "Summary Tiles review karein",
    ),
    "budget-allocation-report.steps.2.caption": (
        "Budget count and totals across the filtered set.",
        "filtered set में budgets की संख्या और कुल योग।",
        "filtered set मधील budgets ची संख्या आणि एकूण बेरीज.",
        "Filtered set mein budgets ka count aur totals.",
    ),
    "budget-allocation-report.steps.3.label": (
        "Drill Into a Line", "किसी Line में Drill करें", "एखाद्या Line मध्ये Drill करा", "Kisi Line mein drill karein",
    ),
    "budget-allocation-report.steps.3.caption": (
        "View items lists the POs and assets that line funds.",
        "View items उन POs और assets को सूचीबद्ध करता है जिन्हें वह line funds करती है।",
        "View items त्या line ने funded केलेल्या POs आणि assets ची यादी दाखवते.",
        "View items un POs aur assets ko list karta hai jinhe wo line fund karti hai.",
    ),
    "budget-allocation-report.fieldRules.0.name": (
        "Fiscal Year", "Fiscal Year", "Fiscal Year", "Fiscal Year",
    ),
    "budget-allocation-report.fieldRules.0.description": (
        "Filters which budget lines load; blank combines all years into one aggregate view.",
        "यह तय करता है कि कौन-सी budget lines load होंगी; खाली छोड़ने पर सभी वर्ष एक aggregate view में मिल जाते हैं।",
        "कोणत्या budget lines लोड होतील हे हे ठरवते; रिकामे ठेवल्यास सर्व वर्षे एका aggregate view मध्ये एकत्र होतात.",
        "Ye decide karta hai ki kaunsi budget lines load hongi; blank chhodne par sabhi years ek aggregate view mein combine ho jaate hain.",
    ),
    "budget-allocation-report.fieldRules.1.name": (
        "Status", "स्थिति", "स्थिती", "Status",
    ),
    "budget-allocation-report.fieldRules.1.description": (
        "Approved (green) vs draft/pending (amber) badge on the budget line itself.",
        "budget line पर ही Approved (हरा) बनाम draft/pending (एम्बर) badge दिखता है।",
        "budget line वरच Approved (हिरवा) विरुद्ध draft/pending (अंबर) badge दिसतो.",
        "Budget line par hi Approved (green) vs draft/pending (amber) badge dikhta hai.",
    ),
    "budget-allocation-report.fieldRules.2.name": (
        "Available", "उपलब्ध", "उपलब्ध", "Available",
    ),
    "budget-allocation-report.fieldRules.2.description": (
        "Approved minus spent; shown in red when negative, meaning the line is over-committed.",
        "Approved में से spent घटाकर निकाला जाता है; negative होने पर लाल रंग में दिखता है, जिसका अर्थ है कि line over-committed है।",
        "Approved मधून spent वजा करून काढले जाते; negative असल्यास लाल रंगात दाखवले जाते, म्हणजे ती line over-committed आहे.",
        "Approved mein se spent minus karke nikala jaata hai; negative hone par red mein dikhta hai, matlab line over-committed hai.",
    ),
    "budget-allocation-report.fieldRules.3.name": (
        "View Items", "View Items", "View Items", "View Items",
    ),
    "budget-allocation-report.fieldRules.3.description": (
        "Opens the drill-down of POs/assets funded by this line; disabled when it funds none yet.",
        "यह line द्वारा funded POs/assets का drill-down खोलता है; अगर अभी तक कुछ भी funded नहीं है तो यह disabled रहता है।",
        "या line ने funded केलेल्या POs/assets चा drill-down उघडतो; अजून काहीही funded नसल्यास तो disabled असतो.",
        "Is line ne funded kiye POs/assets ka drill-down khulta hai; agar abhi tak kuch bhi funded nahi hai to ye disabled rehta hai.",
    ),
    "budget-allocation-report.tip.title": (
        "Filter before trusting totals",
        "Totals पर भरोसा करने से पहले Filter करें",
        "Totals वर विश्वास ठेवण्यापूर्वी Filter करा",
        "Totals par bharosa karne se pehle filter karein",
    ),
    "budget-allocation-report.tip.body": (
        "Leaving Fiscal Year blank sums every year together in the tiles above the table — pick a specific year to see an accurate approved-vs-spent picture for that budget cycle.",
        "Fiscal Year को खाली छोड़ने पर table के ऊपर वाली tiles में सभी वर्षों का योग एक साथ दिख जाता है — किसी विशेष budget cycle के लिए सटीक approved-vs-spent तस्वीर देखने हेतु एक specific वर्ष चुनें।",
        "Fiscal Year रिकामे ठेवल्यास table वरील tiles मध्ये सर्व वर्षांची बेरीज एकत्र दिसते — त्या budget cycle साठी अचूक approved-vs-spent चित्र पाहण्यासाठी एक specific वर्ष निवडा.",
        "Fiscal Year ko blank chhodne par table ke upar wali tiles mein sabhi years ka sum ek saath dikh jaata hai — kisi specific budget cycle ka accurate approved-vs-spent picture dekhne ke liye ek specific year choose 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 BUDGET_ALLOCATION_REPORT.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(BUDGET_ALLOCATION_REPORT)} budget-allocation-report keys.")


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