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

Usage: docker compose exec api python seed_translations_pageinfo_npv_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)
NPV_ANALYSIS = {
    "npv-analysis.title": (
        "Renewal Recommendations",
        "नवीकरण अनुशंसाएं",
        "नूतनीकरण शिफारसी",
        "Renewal Recommendations",
    ),
    "npv-analysis.subtitle": (
        "High-criticality assets flagged as repair-vs-replace candidates",
        "High-criticality assets, जिन्हें repair-vs-replace उम्मीदवार के रूप में चिह्नित किया गया है",
        "High-criticality assets, ज्यांना repair-vs-replace उमेदवार म्हणून चिन्हांकित केले आहे",
        "High-criticality assets jinhe repair-vs-replace candidates ke roop mein flag kiya gaya hai",
    ),
    "npv-analysis.body.0": (
        "High-criticality assets in poor or critical condition — candidates for a repair-vs-replace NPV analysis.",
        "खराब या क्रिटिकल स्थिति वाले High-criticality assets — repair-vs-replace NPV analysis के लिए उम्मीदवार।",
        "खराब किंवा क्रिटिकल स्थितीतील High-criticality assets — repair-vs-replace NPV analysis साठी उमेदवार.",
        "Poor ya critical condition mein High-criticality assets — repair-vs-replace NPV analysis ke liye candidates.",
    ),
    "npv-analysis.body.1": (
        "This list is auto-generated: it surfaces every asset with a criticality score of 4 or higher, ordered highest-first. It does not by itself compute any NPV or TCO numbers — it is the shortlist you work from.",
        "यह सूची auto-generated है: यह 4 या उससे अधिक criticality score वाले हर asset को सामने लाती है, जो highest-first क्रम में है। यह स्वयं कोई NPV या TCO नंबर calculate नहीं करती — यह वह shortlist है जिससे आप काम शुरू करते हैं।",
        "ही यादी auto-generated आहे: ती 4 किंवा त्याहून अधिक criticality score असलेल्या प्रत्येक asset ला समोर आणते, highest-first क्रमाने. ही स्वतः कोणतेही NPV किंवा TCO आकडे calculate करत नाही — ही ती shortlist आहे जिथून तुम्ही काम सुरू करता.",
        "Ye list auto-generated hai: ye 4 ya usse zyada criticality score wale har asset ko highest-first order mein surface karti hai. Ye khud koi NPV ya TCO numbers calculate nahi karti — ye wo shortlist hai jisse aap kaam shuru karte hain.",
    ),
    "npv-analysis.stepsHeading": (
        "From candidate to decision",
        "उम्मीदवार से निर्णय तक",
        "उमेदवारापासून निर्णयापर्यंत",
        "Candidate se decision tak",
    ),
    "npv-analysis.steps.0.label": ("Flagged", "चिह्नित", "चिन्हांकित", "Flag hua"),
    "npv-analysis.steps.0.caption": (
        "Asset criticality score reaches 4 or above.",
        "Asset का criticality score 4 या उससे अधिक हो जाता है।",
        "Asset चा criticality score 4 किंवा त्याहून अधिक होतो.",
        "Asset ka criticality score 4 ya usse zyada ho jaata hai.",
    ),
    "npv-analysis.steps.1.label": ("Listed here", "यहाँ सूचीबद्ध", "इथे सूचीबद्ध", "Yahan list mein"),
    "npv-analysis.steps.1.caption": (
        "Appears in this table with its current lifecycle state.",
        "अपनी वर्तमान lifecycle state के साथ इस table में दिखाई देता है।",
        "स्वतःच्या सध्याच्या lifecycle state सह या table मध्ये दिसते.",
        "Apni current lifecycle state ke saath is table mein dikhta hai.",
    ),
    "npv-analysis.steps.2.label": ("Run Scenario", "Run Scenario", "Run Scenario", "Run Scenario"),
    "npv-analysis.steps.2.caption": (
        "Pick the asset and open Create Scenario to model it.",
        "Asset चुनें और उसे model करने के लिए Create Scenario खोलें।",
        "Asset निवडा आणि त्याचे model करण्यासाठी Create Scenario उघडा.",
        "Asset select karein aur use model karne ke liye Create Scenario kholein.",
    ),
    "npv-analysis.steps.3.label": ("Compare NPV/TCO", "NPV/TCO की तुलना करें", "NPV/TCO ची तुलना करा", "NPV/TCO compare karein"),
    "npv-analysis.steps.3.caption": (
        "Scenario returns the real repair-vs-replace numbers.",
        "Scenario असली repair-vs-replace नंबर देता है।",
        "Scenario खरे repair-vs-replace आकडे देतो.",
        "Scenario asli repair-vs-replace numbers deta hai.",
    ),
    "npv-analysis.fieldRules.0.name": ("Criticality Score", "क्रिटिकैलिटी स्कोर", "क्रिटिकॅलिटी स्कोअर", "Criticality Score"),
    "npv-analysis.fieldRules.0.description": (
        "Numeric rating on the asset record; only assets scoring 4+ appear here.",
        "Asset record पर numeric rating; यहाँ केवल 4+ स्कोर वाले assets दिखते हैं।",
        "Asset record वरील numeric rating; इथे फक्त 4+ score असलेल्या assets दिसतात.",
        "Asset record par numeric rating hoti hai; yahan sirf 4+ score wale assets dikhte hain.",
    ),
    "npv-analysis.fieldRules.1.name": ("Lifecycle State", "लाइफसाइकिल स्टेट", "लाइफसायकल स्टेट", "Lifecycle State"),
    "npv-analysis.fieldRules.1.description": (
        "Asset's current lifecycle stage (e.g. in_operation) — not a physical-condition rating.",
        "Asset की वर्तमान lifecycle stage (जैसे in_operation) — यह कोई physical-condition rating नहीं है।",
        "Asset ची सध्याची lifecycle stage (उदा. in_operation) — ही physical-condition rating नाही.",
        "Asset ki current lifecycle stage (jaise in_operation) — ye physical-condition rating nahi hai.",
    ),
    "npv-analysis.fieldRules.2.name": ("Asset Class", "एसेट क्लास", "ॲसेट क्लास", "Asset Class"),
    "npv-analysis.fieldRules.2.description": (
        "Category the asset belongs to, shown for context when triaging the list.",
        "वह category जिससे asset संबंधित है, list को triage करते समय context के लिए दिखाई जाती है।",
        "Asset ज्या category ची आहे ती, list triage करताना context साठी दाखवली जाते.",
        "Wo category jiske asset belong karta hai, list ko triage karte waqt context ke liye dikhayi jaati hai.",
    ),
    "npv-analysis.fieldRules.3.name": ("Asset Ref", "एसेट रेफ", "ॲसेट रेफ", "Asset Ref"),
    "npv-analysis.fieldRules.3.description": (
        "Unique asset reference — use it to look the asset up in Create Scenario.",
        "Unique asset reference — Create Scenario में asset को खोजने के लिए इसका उपयोग करें।",
        "Unique asset reference — Create Scenario मध्ये asset शोधण्यासाठी याचा वापर करा.",
        "Unique asset reference hai — Create Scenario mein asset ko dhoondhne ke liye ise use karein.",
    ),
    "npv-analysis.tip.title": (
        "Lifecycle state is not a condition rating",
        "Lifecycle state कोई condition rating नहीं है",
        "Lifecycle state ही condition rating नाही",
        "Lifecycle state condition rating nahi hai",
    ),
    "npv-analysis.tip.body": (
        "There is no physical-condition assessment in this system yet, so this list can't filter by poor/critical condition as the name implies — it only filters by criticality score. Treat it as a triage shortlist, and get the actual repair-vs-replace numbers by running a scenario on the asset.",
        "इस सिस्टम में अभी तक कोई physical-condition assessment नहीं है, इसलिए यह list नाम के अनुसार poor/critical condition के आधार पर filter नहीं कर सकती — यह केवल criticality score के आधार पर filter करती है। इसे एक triage shortlist मानें, और asset पर scenario run करके असली repair-vs-replace नंबर पाएं।",
        "या system मध्ये अजून कोणतेही physical-condition assessment नाही, त्यामुळे ही list नावाप्रमाणे poor/critical condition नुसार filter करू शकत नाही — ती फक्त criticality score नुसार filter करते. हिला triage shortlist समजा, आणि asset वर scenario run करून खरे repair-vs-replace आकडे मिळवा.",
        "Is system mein abhi tak koi physical-condition assessment nahi hai, isliye ye list naam ke hisaab se poor/critical condition ke basis par filter nahi kar sakti — ye sirf criticality score ke basis par filter karti hai. Ise ek triage shortlist maanein, aur asset par scenario run karke asli repair-vs-replace numbers paayein.",
    ),
}


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 NPV_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(NPV_ANALYSIS)} npv-analysis keys.")


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