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

Usage: docker compose exec api python seed_translations_pageinfo_tco_analysis.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)
TCO_ANALYSIS = {
    "tco-analysis.title": (
        "Total Cost of Ownership",
        "टोटल कॉस्ट ऑफ ओनरशिप",
        "टोटल कॉस्ट ऑफ ओनरशिप",
        "Total Cost of Ownership",
    ),
    "tco-analysis.subtitle": (
        "How this chart is built and what the bars mean",
        "यह chart कैसे बनता है और bars का क्या मतलब है",
        "हे chart कसे तयार होते आणि bars चा अर्थ काय आहे",
        "Ye chart kaise banta hai aur bars ka kya matlab hai",
    ),
    "tco-analysis.body.0": (
        "TCO comparison across repair/replace options for a scenario's assets.",
        "किसी scenario के assets के लिए repair/replace options में TCO तुलना।",
        "एखाद्या scenario च्या assets साठी repair/replace options मधील TCO तुलना.",
        "Kisi scenario ke assets ke liye repair/replace options ke beech TCO comparison.",
    ),
    "tco-analysis.body.1": (
        "This is a chart-only lens on the same scenario data Scenario Submission Review lists — it re-fetches and re-ranks by TCO instead of showing a row-by-row list.",
        "यह उसी scenario data पर एक chart-only नज़रिया है जिसे Scenario Submission Review लिस्ट करता है — यह row-by-row list दिखाने के बजाय TCO के अनुसार दोबारा fetch और rank करता है।",
        "हे त्याच scenario डेटावर एक chart-only दृष्टिकोन आहे जो Scenario Submission Review लिस्ट करते — हे row-by-row list दाखवण्याऐवजी TCO नुसार पुन्हा fetch आणि rank करते.",
        "Ye usi scenario data par ek chart-only lens hai jise Scenario Submission Review list karta hai — ye row-by-row list dikhane ke bajaye TCO ke hisaab se dobara fetch aur rank karta hai.",
    ),
    "tco-analysis.stepsHeading": (
        "How to read this page",
        "इस पेज को कैसे पढ़ें",
        "हे पेज कसे वाचावे",
        "Is page ko kaise padhein",
    ),
    "tco-analysis.steps.0.label": ("Create Scenario", "Scenario बनाएं", "Scenario तयार करा", "Scenario Create karein"),
    "tco-analysis.steps.0.caption": (
        "Build a repair-vs-replace scenario first (needs investment:create).",
        "पहले एक repair-vs-replace scenario बनाएं (investment:create ज़रूरी है)।",
        "आधी एक repair-vs-replace scenario तयार करा (investment:create आवश्यक आहे).",
        "Pehle ek repair-vs-replace scenario banayein (investment:create chahiye).",
    ),
    "tco-analysis.steps.1.label": ("Enter ID", "ID दर्ज करें", "ID प्रविष्ट करा", "ID Enter karein"),
    "tco-analysis.steps.1.caption": (
        "Paste the scenario's ID into the field below.",
        "नीचे दिए गए field में scenario की ID पेस्ट करें।",
        "खालील field मध्ये scenario ची ID पेस्ट करा.",
        "Neeche diye field mein scenario ki ID paste karein.",
    ),
    "tco-analysis.steps.2.label": ("Load", "Load करें", "Load करा", "Load karein"),
    "tco-analysis.steps.2.caption": (
        "Fetches the scenario and recalculates NPV/TCO live.",
        "यह scenario को fetch करता है और NPV/TCO को live रूप से दोबारा calculate करता है।",
        "हे scenario fetch करते आणि NPV/TCO लाइव्ह पुन्हा calculate करते.",
        "Ye scenario ko fetch karta hai aur NPV/TCO ko live recalculate karta hai.",
    ),
    "tco-analysis.steps.3.label": ("Compare Bars", "Bars की तुलना करें", "Bars ची तुलना करा", "Bars Compare karein"),
    "tco-analysis.steps.3.caption": (
        "One group per asset; one color per option type.",
        "प्रत्येक asset के लिए एक group; प्रत्येक option type के लिए एक रंग।",
        "प्रत्येक asset साठी एक group; प्रत्येक option type साठी एक रंग.",
        "Har asset ke liye ek group; har option type ke liye ek color.",
    ),
    "tco-analysis.fieldRules.0.name": ("Scenario ID", "Scenario ID", "Scenario ID", "Scenario ID"),
    "tco-analysis.fieldRules.0.description": (
        "Load stays disabled until this is filled in; must match an existing scenario's ID.",
        "जब तक यह भरा नहीं जाता, Load disabled रहता है; यह किसी मौजूदा scenario की ID से मेल खाना चाहिए।",
        "हे भरले जात नाही तोपर्यंत Load disabled राहते; हे अस्तित्वात असलेल्या scenario च्या ID शी जुळले पाहिजे.",
        "Jab tak ye fill nahi hota, Load disabled rehta hai; ye kisi existing scenario ki ID se match hona chahiye.",
    ),
    "tco-analysis.fieldRules.1.name": ("Asset (x-axis)", "Asset (x-axis)", "Asset (x-axis)", "Asset (x-axis)"),
    "tco-analysis.fieldRules.1.description": (
        "One bar group per asset in the scenario.",
        "scenario में प्रत्येक asset के लिए एक bar group।",
        "scenario मधील प्रत्येक asset साठी एक bar group.",
        "Scenario mein har asset ke liye ek bar group.",
    ),
    "tco-analysis.fieldRules.2.name": ("Option type (legend)", "Option type (legend)", "Option type (legend)", "Option type (legend)"),
    "tco-analysis.fieldRules.2.description": (
        "Color-coded series, e.g. repair vs. replace, one per option the scenario evaluated.",
        "Color-coded series, जैसे repair बनाम replace, scenario द्वारा evaluate किए गए प्रत्येक option के लिए एक।",
        "Color-coded series, उदा. repair विरुद्ध replace, scenario ने evaluate केलेल्या प्रत्येक option साठी एक.",
        "Color-coded series, jaise repair vs. replace, scenario ne jo bhi options evaluate kiye unme se har ek ke liye ek.",
    ),
    "tco-analysis.fieldRules.3.name": ("TCO (y-axis)", "TCO (y-axis)", "TCO (y-axis)", "TCO (y-axis)"),
    "tco-analysis.fieldRules.3.description": (
        "Total cost of ownership over the scenario's horizon for that option.",
        "उस option के लिए scenario के horizon पर कुल total cost of ownership।",
        "त्या option साठी scenario च्या horizon वरील एकूण total cost of ownership.",
        "Us option ke liye scenario ke horizon par total cost of ownership.",
    ),
    "tco-analysis.tip.title": (
        "Numbers are recalculated, not stored",
        "Numbers दोबारा calculate होते हैं, स्टोर नहीं",
        "Numbers पुन्हा calculate होतात, साठवले जात नाहीत",
        "Numbers dobara calculate hote hain, store nahi hote",
    ),
    "tco-analysis.tip.body": (
        "Every Load re-runs the NPV/TCO calculation against current asset data — it isn't a cached snapshot from when the scenario was created. If asset costs or condition changed since then, the bars here can differ from what was originally approved.",
        "हर Load, current asset data के आधार पर NPV/TCO calculation को दोबारा run करता है — यह scenario बनाए जाने के समय का cached snapshot नहीं है। अगर तब से asset की costs या condition बदल गई है, तो यहाँ के bars मूल रूप से approved चीज़ों से भिन्न हो सकते हैं।",
        "प्रत्येक Load, current asset डेटावर आधारित NPV/TCO calculation पुन्हा run करते — हे scenario तयार केले तेव्हाचे cached snapshot नाही. जर तेव्हापासून asset च्या costs किंवा condition मध्ये बदल झाला असेल, तर येथील bars मूळतः approved केलेल्यापेक्षा वेगळे असू शकतात.",
        "Har Load, current asset data ke against NPV/TCO calculation ko dobara run karta hai — ye scenario banaye jaane ke time ka cached snapshot nahi hai. Agar tab se asset ki costs ya condition change hui hai, to yahan ke bars originally approved cheezon se different ho sakte 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 TCO_ANALYSIS.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(TCO_ANALYSIS)} tco-analysis keys.")


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