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

Usage: docker compose exec api python seed_translations_pageinfo_budget_impact.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_IMPACT = {
    "budget-impact.title": (
        "Budget Impact",
        "बजट प्रभाव",
        "बजेट परिणाम",
        "Budget Impact",
    ),
    "budget-impact.subtitle": (
        "Year-end forecast and budget-vs-actual variance",
        "वर्ष-अंत पूर्वानुमान और बजट-बनाम-वास्तविक अंतर",
        "वर्षअखेर अंदाज आणि बजेट-वि-प्रत्यक्ष फरक",
        "Year-end forecast aur budget-vs-actual variance",
    ),
    "budget-impact.body.0": (
        "Year-end forecast (year-to-date actuals plus commitments plus burn rate) and budget-vs-actual variance.",
        "वर्ष-अंत पूर्वानुमान (year-to-date actuals, commitments और burn rate का योग) और बजट-बनाम-वास्तविक अंतर।",
        "वर्षअखेर अंदाज (year-to-date actuals, commitments आणि burn rate ची बेरीज) आणि बजेट-वि-प्रत्यक्ष फरक.",
        "Year-end forecast (year-to-date actuals plus commitments plus burn rate) aur budget-vs-actual variance.",
    ),
    "budget-impact.body.1": (
        "Both reports are scoped to the selected fiscal year; the variance table can additionally be narrowed to one cost centre.",
        "दोनों reports चयनित fiscal year तक सीमित हैं; variance table को इसके अतिरिक्त एक cost centre तक संकुचित किया जा सकता है।",
        "दोन्ही reports निवडलेल्या fiscal year पुरत्या मर्यादित आहेत; variance table अतिरिक्त एका cost centre पुरते संकुचित करता येते.",
        "Dono reports selected fiscal year tak scoped hain; variance table ko additionally ek cost centre tak narrow kiya ja sakta hai.",
    ),
    "budget-impact.stepsHeading": (
        "How to run this report",
        "यह report कैसे चलाएं",
        "हा report कसा चालवायचा",
        "Ye report kaise run karein",
    ),
    "budget-impact.steps.0.label": (
        "Pick Fiscal Year",
        "Fiscal Year चुनें",
        "Fiscal Year निवडा",
        "Fiscal Year pick karein",
    ),
    "budget-impact.steps.0.caption": (
        "Defaults to the current fiscal year; both reports are scoped to it.",
        "डिफ़ॉल्ट रूप से current fiscal year सेट होता है; दोनों reports इसी तक सीमित हैं।",
        "डीफॉल्टनुसार current fiscal year सेट होते; दोन्ही reports याच पुरते मर्यादित असतात.",
        "Default current fiscal year hota hai; dono reports isi tak scoped hain.",
    ),
    "budget-impact.steps.1.label": (
        "Filter Cost Centre",
        "Cost Centre फ़िल्टर करें",
        "Cost Centre फिल्टर करा",
        "Cost Centre filter karein",
    ),
    "budget-impact.steps.1.caption": (
        "Optional — narrows only the variance table, not the forecast summary.",
        "वैकल्पिक — यह केवल variance table को संकुचित करता है, forecast summary को नहीं।",
        "ऐच्छिक — हे फक्त variance table संकुचित करते, forecast summary ला नाही.",
        "Optional hai — sirf variance table ko narrow karta hai, forecast summary ko nahi.",
    ),
    "budget-impact.steps.2.label": (
        "Run Reports",
        "Reports चलाएं",
        "Reports चालवा",
        "Reports run karein",
    ),
    "budget-impact.steps.2.caption": (
        "Fetches the forecast and variance report together.",
        "forecast और variance report को एक साथ प्राप्त करता है।",
        "forecast आणि variance report एकत्र मिळवते.",
        "Forecast aur variance report ko ek saath fetch karta hai.",
    ),
    "budget-impact.steps.3.label": (
        "Review Results",
        "परिणामों की समीक्षा करें",
        "निकालांचे पुनरावलोकन करा",
        "Results review karein",
    ),
    "budget-impact.steps.3.caption": (
        "Compare forecast year-end and burn rate against per-line utilisation.",
        "forecast year-end और burn rate की तुलना per-line utilisation से करें।",
        "forecast year-end आणि burn rate ची तुलना per-line utilisation शी करा.",
        "Forecast year-end aur burn rate ko per-line utilisation ke against compare karein.",
    ),
    "budget-impact.fieldRules.0.name": (
        "Fiscal Year",
        "Fiscal Year",
        "Fiscal Year",
        "Fiscal Year",
    ),
    "budget-impact.fieldRules.0.description": (
        "Scopes both the forecast and variance queries; format is FY2026-27.",
        "forecast और variance दोनों queries को सीमित करता है; format FY2026-27 है।",
        "forecast आणि variance या दोन्ही queries मर्यादित करते; format FY2026-27 आहे.",
        "Forecast aur variance dono queries ko scope karta hai; format FY2026-27 hota hai.",
    ),
    "budget-impact.fieldRules.1.name": (
        "Cost Centre",
        "Cost Centre",
        "Cost Centre",
        "Cost Centre",
    ),
    "budget-impact.fieldRules.1.description": (
        "Optional filter — applies only to the variance table, leaving the forecast unaffected.",
        "वैकल्पिक filter — यह केवल variance table पर लागू होता है, forecast अप्रभावित रहता है।",
        "ऐच्छिक filter — हे फक्त variance table ला लागू होते, forecast वर परिणाम होत नाही.",
        "Optional filter hai — sirf variance table par apply hota hai, forecast unaffected rehta hai.",
    ),
    "budget-impact.fieldRules.2.name": (
        "Status",
        "Status",
        "Status",
        "Status",
    ),
    "budget-impact.fieldRules.2.description": (
        "The budget line's own approval state (pending/approved), not a spend-health flag.",
        "यह budget line की अपनी approval स्थिति (pending/approved) है, न कि कोई spend-health flag।",
        "ही budget line ची स्वतःची approval स्थिती (pending/approved) आहे, spend-health flag नाही.",
        "Ye budget line ki apni approval state hai (pending/approved), koi spend-health flag nahi.",
    ),
    "budget-impact.fieldRules.3.name": (
        "Available",
        "Available",
        "Available",
        "Available",
    ),
    "budget-impact.fieldRules.3.description": (
        "Approved minus committed minus actual; goes negative once a line is overcommitted.",
        "Approved में से committed और actual घटाकर मिलता है; एक बार line overcommitted होने पर यह negative हो जाता है।",
        "Approved मधून committed आणि actual वजा करून मिळते; एकदा line overcommitted झाली की ते negative होते.",
        "Approved minus committed minus actual hota hai; ek baar line overcommitted ho jaaye to ye negative ho jaata hai.",
    ),
    "budget-impact.tip.title": (
        "Forecast and variance don't share a scope",
        "Forecast और variance का scope एक जैसा नहीं है",
        "Forecast आणि variance चा scope सारखा नाही",
        "Forecast aur variance ka scope same nahi hai",
    ),
    "budget-impact.tip.body": (
        "Year-End Forecast only sums budgets with status = approved. The Variance table includes every budget line for the fiscal year regardless of approval status, so its totals can exceed the forecast summary above — especially early in the year when many lines are still pending.",
        "Year-End Forecast केवल उन budgets को जोड़ता है जिनका status = approved है। Variance table में approval status की परवाह किए बिना उस fiscal year की हर budget line शामिल होती है, इसलिए इसका total ऊपर दिए forecast summary से अधिक हो सकता है — विशेष रूप से वर्ष की शुरुआत में जब कई lines अभी भी pending होती हैं।",
        "Year-End Forecast फक्त status = approved असलेल्या budgets ची बेरीज करते. Variance table मध्ये approval status कशीही असो, त्या fiscal year च्या प्रत्येक budget line चा समावेश असतो, त्यामुळे त्याचा total वरील forecast summary पेक्षा जास्त असू शकतो — विशेषतः वर्षाच्या सुरुवातीला जेव्हा अनेक lines अजूनही pending असतात.",
        "Year-End Forecast sirf un budgets ko sum karta hai jinka status = approved hai. Variance table mein approval status kuch bhi ho, us fiscal year ki har budget line include hoti hai, isliye iska total upar wale forecast summary se zyada ho sakta hai — especially year ki shuruaat mein jab kaafi lines abhi bhi pending hoti hain.",
    ),
}


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_IMPACT.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_IMPACT)} budget-impact keys.")


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