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

Usage: docker compose exec api python seed_translations_pageinfo_scenario_comparison.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)
SCENARIO_COMPARISON = {
    "scenario-comparison.title": (
        "Capex Scenario Comparison",
        "कैपेक्स सिनेरियो कम्पैरिज़न",
        "कॅपेक्स सिनॅरिओ कम्पॅरिझन",
        "Capex Scenario Comparison",
    ),
    "scenario-comparison.subtitle": (
        "Compare logged capex scenarios side by side",
        "लॉग किए गए capex scenarios की साथ-साथ तुलना करें",
        "लॉग केलेल्या capex scenarios ची शेजारी-शेजारी तुलना करा",
        "Logged capex scenarios ko side by side compare karein",
    ),
    "scenario-comparison.body.0": (
        "Select up to 3 logged capex scenarios to compare side by side.",
        "तुलना के लिए साथ-साथ अधिकतम 3 logged capex scenarios चुनें।",
        "तुलना करण्यासाठी जास्तीत जास्त 3 logged capex scenarios शेजारी-शेजारी निवडा.",
        "Side by side compare karne ke liye maximum 3 logged capex scenarios select karein.",
    ),
    "scenario-comparison.body.1": (
        "This view only compares the name, description, and horizon already logged for each scenario. For NPV/TCO/risk/payback modeling, open the NPV Analysis or TCO Analysis tools linked from the comparison panel.",
        "यह view केवल प्रत्येक scenario के लिए पहले से logged name, description, और horizon की तुलना करता है। NPV/TCO/risk/payback modeling के लिए, comparison panel से लिंक किए गए NPV Analysis या TCO Analysis tools खोलें।",
        "हे view फक्त प्रत्येक scenario साठी आधीच logged असलेले name, description, आणि horizon यांची तुलना करते. NPV/TCO/risk/payback modeling साठी, comparison panel मधून लिंक केलेले NPV Analysis किंवा TCO Analysis tools उघडा.",
        "Ye view sirf har scenario ke liye pehle se logged name, description, aur horizon ki tulna karta hai. NPV/TCO/risk/payback modeling ke liye, comparison panel se linked NPV Analysis ya TCO Analysis tools open karein.",
    ),
    "scenario-comparison.stepsHeading": (
        "How this page works",
        "यह पेज कैसे काम करता है",
        "हे पेज कसे कार्य करते",
        "Ye page kaise kaam karta hai",
    ),
    "scenario-comparison.steps.0.label": ("Browse", "ब्राउज़ करें", "ब्राउझ करा", "Browse"),
    "scenario-comparison.steps.0.caption": (
        "All logged capex scenarios load into the table below.",
        "सभी logged capex scenarios नीचे दी गई table में load होते हैं।",
        "सर्व logged capex scenarios खालील table मध्ये load होतात.",
        "Sabhi logged capex scenarios neeche table mein load ho jaate hain.",
    ),
    "scenario-comparison.steps.1.label": ("Select (up to 3)", "चुनें (अधिकतम 3)", "निवडा (जास्तीत जास्त 3)", "Select karein (max 3)"),
    "scenario-comparison.steps.1.caption": (
        "Check the box next to each scenario you want to compare.",
        "जिस scenario की तुलना करनी है, उसके बगल वाला box चेक करें।",
        "ज्या scenario ची तुलना करायची आहे, त्याच्या शेजारील box चेक करा.",
        "Jis scenario ko compare karna hai uske bagal wala box check karein.",
    ),
    "scenario-comparison.steps.2.label": ("Compare", "तुलना करें", "तुलना करा", "Compare"),
    "scenario-comparison.steps.2.caption": (
        "Selected scenarios render side by side below the table.",
        "चुने गए scenarios table के नीचे साथ-साथ render होते हैं।",
        "निवडलेले scenarios table खाली शेजारी-शेजारी render होतात.",
        "Selected scenarios table ke neeche side by side render hote hain.",
    ),
    "scenario-comparison.steps.3.label": ("Deep dive", "गहन विश्लेषण", "सखोल विश्लेषण", "Deep dive"),
    "scenario-comparison.steps.3.caption": (
        "Open NPV/TCO Analysis for full financial modeling.",
        "पूर्ण financial modeling के लिए NPV/TCO Analysis खोलें।",
        "संपूर्ण financial modeling साठी NPV/TCO Analysis उघडा.",
        "Poori financial modeling ke liye NPV/TCO Analysis open karein.",
    ),
    "scenario-comparison.fieldRules.0.name": ("Select", "चुनें", "निवडा", "Select"),
    "scenario-comparison.fieldRules.0.description": (
        "Adds or removes a scenario from the comparison; capped at 3 at a time.",
        "comparison में से किसी scenario को जोड़ता या हटाता है; एक बार में अधिकतम 3 तक सीमित।",
        "comparison मधून एखादी scenario जोडते किंवा काढते; एका वेळी जास्तीत जास्त 3 पर्यंत मर्यादित.",
        "Comparison mein scenario add ya remove karta hai; ek baar mein max 3 tak capped hai.",
    ),
    "scenario-comparison.fieldRules.1.name": ("Scenario Name", "सिनेरियो नाम", "सिनेरिओ नाव", "Scenario Name"),
    "scenario-comparison.fieldRules.1.description": (
        "Identifies the scenario; set when it was originally logged.",
        "scenario की पहचान करता है; यह तब सेट किया जाता है जब इसे मूल रूप से log किया गया था।",
        "scenario ची ओळख करते; हे मूळतः log केले तेव्हा सेट केले जाते.",
        "Scenario ko identify karta hai; jab ye originally log hua tha tab set kiya gaya tha.",
    ),
    "scenario-comparison.fieldRules.2.name": ("Description", "विवरण", "वर्णन", "Description"),
    "scenario-comparison.fieldRules.2.description": (
        "Optional free-text notes on the scenario's assumptions.",
        "scenario की assumptions पर वैकल्पिक free-text notes।",
        "scenario च्या assumptions वर पर्यायी free-text notes.",
        "Scenario ki assumptions par optional free-text notes.",
    ),
    "scenario-comparison.fieldRules.3.name": ("Horizon (Years)", "होराइज़न (वर्ष)", "होरायझन (वर्षे)", "Horizon (Years)"),
    "scenario-comparison.fieldRules.3.description": (
        "Investment horizon (typically 10/20/30 years) the scenario's projections are based on.",
        "investment horizon (आमतौर पर 10/20/30 वर्ष) जिस पर scenario के projections आधारित हैं।",
        "investment horizon (सामान्यतः 10/20/30 वर्षे) ज्यावर scenario चे projections आधारित आहेत.",
        "Investment horizon (typically 10/20/30 saal) jispar scenario ke projections based hain.",
    ),
    "scenario-comparison.tip.title": (
        "Selection caps silently at 3",
        "चयन silently 3 पर सीमित हो जाता है",
        "निवड silently 3 वर मर्यादित होते",
        "Selection silently 3 par cap ho jaata hai",
    ),
    "scenario-comparison.tip.body": (
        "The first 2 scenarios load pre-selected automatically. Checking a 4th box does nothing — no toast or disabled state appears — so uncheck one first if you want to swap it out.",
        "पहले 2 scenarios automatically pre-selected load होते हैं। चौथा box चेक करने से कुछ नहीं होता — न कोई toast दिखता है, न disabled state — इसलिए स्वैप करने के लिए पहले एक को uncheck करें।",
        "पहिले 2 scenarios automatically pre-selected load होतात. चौथा box चेक केल्याने काहीही होत नाही — ना toast दिसतो, ना disabled state — त्यामुळे स्वॅप करण्यासाठी आधी एक uncheck करा.",
        "Pehle 2 scenarios automatically pre-selected load hote hain. 4th box check karne se kuch nahi hota — na toast aata hai na disabled state — isliye swap karne ke liye pehle ek ko uncheck 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 SCENARIO_COMPARISON.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(SCENARIO_COMPARISON)} scenario-comparison keys.")


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