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

Usage: docker compose exec api python seed_translations_pageinfo_scenario_review.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_REVIEW = {
    "scenario-review.title": (
        "Investment Scenario Review",
        "इन्वेस्टमेंट सिनेरियो रिव्यू",
        "इन्व्हेस्टमेंट सिनॅरिओ रिव्ह्यू",
        "Investment Scenario Review",
    ),
    "scenario-review.body.0": (
        "Repair-vs-replace results per asset, plus an ISO 55001-aligned SAMP capital plan export.",
        "प्रत्येक asset के लिए repair-vs-replace results, साथ ही एक ISO 55001-अनुरूप SAMP capital plan export।",
        "प्रत्येक asset साठी repair-vs-replace results, तसेच एक ISO 55001-अनुरूप SAMP capital plan export.",
        "Har asset ke liye repair-vs-replace results, plus ek ISO 55001-aligned SAMP capital plan export.",
    ),
    "scenario-review.body.1": (
        "Results are recalculated live each time you load a scenario ID — this page never shows a stale cached copy.",
        "जब भी आप कोई scenario ID load करते हैं, results लाइव रीकैलकुलेट होते हैं — यह पेज कभी भी stale cached copy नहीं दिखाता।",
        "जेव्हा जेव्हा तुम्ही एखादी scenario ID load करता, तेव्हा results लाइव्ह रीकॅल्क्युलेट होतात — हे पेज कधीही stale cached copy दाखवत नाही.",
        "Jab bhi aap koi scenario ID load karte ho, results live recalculate hote hain — ye page kabhi bhi stale cached copy nahi dikhata.",
    ),
    "scenario-review.stepsHeading": (
        "How to use this page",
        "इस पेज का उपयोग कैसे करें",
        "हे पेज कसे वापरावे",
        "Ye page kaise use karein",
    ),
    "scenario-review.steps.0.label": ("Enter Scenario ID", "Scenario ID दर्ज करें", "Scenario ID एंटर करा", "Scenario ID enter karein"),
    "scenario-review.steps.0.caption": (
        "Paste the ID from Create Scenario or the Capital Plan registry.",
        "Create Scenario या Capital Plan registry से ID पेस्ट करें।",
        "Create Scenario किंवा Capital Plan registry मधून ID पेस्ट करा.",
        "Create Scenario ya Capital Plan registry se ID paste karein.",
    ),
    "scenario-review.steps.1.label": ("Load Results", "Results Load करें", "Results Load करा", "Results Load karein"),
    "scenario-review.steps.1.caption": (
        "Runs the repair-vs-replace calculation fresh for every asset in the scenario.",
        "यह scenario के हर asset के लिए repair-vs-replace calculation फिर से चलाता है।",
        "हे scenario मधील प्रत्येक asset साठी repair-vs-replace calculation पुन्हा चालवते.",
        "Ye scenario ke har asset ke liye repair-vs-replace calculation fresh se run karta hai.",
    ),
    "scenario-review.steps.2.label": ("Review Options", "Options Review करें", "Options Review करा", "Options Review karein"),
    "scenario-review.steps.2.caption": (
        "Compare NPV/TCO per option; the recommended option is highlighted per asset.",
        "प्रत्येक option के NPV/TCO की तुलना करें; प्रत्येक asset के लिए recommended option हाइलाइट किया जाता है।",
        "प्रत्येक option चे NPV/TCO तुलना करा; प्रत्येक asset साठी recommended option हायलाइट केला जातो.",
        "Har option ka NPV/TCO compare karein; har asset ke liye recommended option highlight hota hai.",
    ),
    "scenario-review.steps.3.label": ("SAMP Export", "SAMP Export", "SAMP Export", "SAMP Export"),
    "scenario-review.steps.3.caption": (
        "Download the ISO 55001-aligned capital plan as JSON once results are loaded.",
        "Results load होने के बाद ISO 55001-अनुरूप capital plan को JSON के रूप में डाउनलोड करें।",
        "Results load झाल्यानंतर ISO 55001-अनुरूप capital plan JSON स्वरूपात डाउनलोड करा.",
        "Results load hone ke baad ISO 55001-aligned capital plan ko JSON format mein download karein.",
    ),
    "scenario-review.fieldRules.0.name": ("Scenario ID", "Scenario ID", "Scenario ID", "Scenario ID"),
    "scenario-review.fieldRules.0.description": (
        "Must belong to an existing scenario; Load stays disabled until this is filled in.",
        "यह किसी मौजूदा scenario से संबंधित होना चाहिए; जब तक यह भरा नहीं जाता, Load बटन disabled रहता है।",
        "हे एखाद्या existing scenario शी संबंधित असणे आवश्यक आहे; हे भरले जाईपर्यंत Load बटण disabled राहते.",
        "Ye kisi existing scenario se belong karna chahiye; jab tak ye fill nahi hota, Load button disabled rehta hai.",
    ),
    "scenario-review.fieldRules.1.name": ("Option", "Option", "Option", "Option"),
    "scenario-review.fieldRules.1.description": (
        "Repair or replace option evaluated for the asset; the recommended one is bolded.",
        "asset के लिए मूल्यांकित repair या replace option; recommended option को बोल्ड किया जाता है।",
        "asset साठी मूल्यांकन केलेला repair किंवा replace option; recommended option बोल्ड केला जातो.",
        "Asset ke liye evaluate kiya gaya repair ya replace option; recommended option ko bold kiya jaata hai.",
    ),
    "scenario-review.fieldRules.2.name": ("NPV", "NPV", "NPV", "NPV"),
    "scenario-review.fieldRules.2.description": (
        "Net present value of the option over the scenario's horizon, at its discount rate.",
        "scenario के horizon के दौरान, उसके discount rate पर option का net present value।",
        "scenario च्या horizon दरम्यान, त्याच्या discount rate वर option चे net present value.",
        "Scenario ke horizon ke dauran, uske discount rate par option ka net present value.",
    ),
    "scenario-review.fieldRules.3.name": ("TCO", "TCO", "TCO", "TCO"),
    "scenario-review.fieldRules.3.description": (
        "Total cost of ownership for the option across the same horizon.",
        "उसी horizon के दौरान option के लिए total cost of ownership।",
        "त्याच horizon दरम्यान option साठी total cost of ownership.",
        "Usi horizon ke dauran option ke liye total cost of ownership.",
    ),
    "scenario-review.fieldRules.4.name": ("Recommended", "Recommended", "Recommended", "Recommended"),
    "scenario-review.fieldRules.4.description": (
        "Badge shown per asset, driven by the backend's own lowest-NPV/TCO pick, not user selection.",
        "प्रत्येक asset के लिए दिखाया गया badge, जो backend के अपने lowest-NPV/TCO चयन से तय होता है, न कि user के चयन से।",
        "प्रत्येक asset साठी दाखवलेला badge, जो backend च्या स्वतःच्या lowest-NPV/TCO निवडीवर आधारित असतो, user च्या निवडीवर नाही.",
        "Har asset ke liye dikhaya gaya badge, jo backend ke apne lowest-NPV/TCO pick se decide hota hai, user selection se nahi.",
    ),
    "scenario-review.tip.title": (
        "No approval step here",
        "यहाँ कोई approval step नहीं है",
        "इथे कोणताही approval step नाही",
        "Yahan koi approval step nahi hai",
    ),
    "scenario-review.tip.body": (
        "This page only recalculates and displays results — there is no approve/reject workflow behind it. To act on a scenario, use the SAMP export and route the capital plan through your own governance process.",
        "यह पेज केवल results को रीकैलकुलेट और डिस्प्ले करता है — इसके पीछे कोई approve/reject workflow नहीं है। किसी scenario पर कार्रवाई करने के लिए, SAMP export का उपयोग करें और capital plan को अपनी governance process के माध्यम से रूट करें।",
        "हे पेज फक्त results रीकॅल्क्युलेट आणि डिस्प्ले करते — याच्यामागे कोणताही approve/reject workflow नाही. एखाद्या scenario वर कारवाई करण्यासाठी, SAMP export वापरा आणि capital plan तुमच्या स्वतःच्या governance process द्वारे रूट करा.",
        "Ye page sirf results ko recalculate aur display karta hai — iske peeche koi approve/reject workflow nahi hai. Kisi scenario par action lene ke liye, SAMP export use karein aur capital plan ko apni governance process ke through route 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_REVIEW.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_REVIEW)} scenario-review keys.")


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