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

Usage: docker compose exec api python seed_translations_pageinfo_planning_dashboard.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)
PLANNING_DASHBOARD = {
    "planning-dashboard.title": (
        "Planning Dashboard",
        "प्लानिंग डैशबोर्ड",
        "प्लॅनिंग डॅशबोर्ड",
        "Planning Dashboard",
    ),
    "planning-dashboard.subtitle": (
        "Capex scenario hub and entry point to portfolio, TCO, NPV and budget analysis",
        "Capex scenario hub और portfolio, TCO, NPV तथा budget analysis का प्रवेश बिंदु",
        "Capex scenario hub आणि portfolio, TCO, NPV व budget analysis साठीचा प्रवेश बिंदू",
        "Capex scenario hub aur portfolio, TCO, NPV aur budget analysis ka entry point",
    ),
    "planning-dashboard.body.0": (
        "This dashboard is a launch pad, not a form: the KPI cards and Capex Scenarios table are read straight from the planner backend, and every button here routes you to the actual screen that does the work.",
        "यह dashboard एक launch pad है, कोई form नहीं: KPI cards और Capex Scenarios table सीधे planner backend से पढ़े जाते हैं, और यहाँ हर button आपको उस असली screen पर ले जाता है जहाँ वास्तविक काम होता है।",
        "हे dashboard एक launch pad आहे, फॉर्म नाही: KPI cards आणि Capex Scenarios table थेट planner backend मधून वाचल्या जातात, आणि इथला प्रत्येक button तुम्हाला त्या खऱ्या screen वर नेतो जिथे प्रत्यक्ष काम होते.",
        "Ye dashboard ek launch pad hai, form nahi: KPI cards aur Capex Scenarios table seedhe planner backend se read hoti hain, aur yahan har button aapko us asli screen par le jaata hai jahan actual kaam hota hai.",
    ),
    "planning-dashboard.body.1": (
        "Use it to see what's already logged (investment backlog, renewals due, budget utilisation, scenario count), then jump into a scenario's Portfolio, TCO, NPV or Budget Impact analysis without hunting through the sidebar.",
        "इसका उपयोग यह देखने के लिए करें कि पहले से क्या दर्ज है (investment backlog, renewals due, budget utilisation, scenario count), फिर sidebar में ढूँढ़े बिना सीधे किसी scenario के Portfolio, TCO, NPV या Budget Impact analysis में जाएँ।",
        "आधीच काय नोंदवले गेले आहे हे पाहण्यासाठी याचा वापर करा (investment backlog, renewals due, budget utilisation, scenario count), नंतर sidebar मध्ये शोधल्याशिवाय थेट एखाद्या scenario च्या Portfolio, TCO, NPV किंवा Budget Impact analysis मध्ये जा.",
        "Isko use karo ye dekhne ke liye ki already kya logged hai (investment backlog, renewals due, budget utilisation, scenario count), phir sidebar mein dhundhe bina directly kisi scenario ke Portfolio, TCO, NPV ya Budget Impact analysis mein jump karo.",
    ),
    "planning-dashboard.stepsHeading": (
        "Strategic planning workflow",
        "रणनीतिक planning workflow",
        "धोरणात्मक planning workflow",
        "Strategic planning workflow",
    ),
    "planning-dashboard.steps.0.label": ("Review Portfolio", "Portfolio की समीक्षा करें", "Portfolio चा आढावा घ्या", "Portfolio Review karo"),
    "planning-dashboard.steps.0.caption": (
        "Survey existing assets before proposing new capex",
        "नया capex प्रस्तावित करने से पहले मौजूदा assets का सर्वेक्षण करें",
        "नवीन capex प्रस्तावित करण्यापूर्वी विद्यमान assets चे सर्वेक्षण करा",
        "Naya capex propose karne se pehle existing assets ka survey karo",
    ),
    "planning-dashboard.steps.1.label": ("Create Scenario", "Scenario बनाएँ", "Scenario तयार करा", "Scenario Create karo"),
    "planning-dashboard.steps.1.caption": (
        "Log a named capex scenario with a 10/20/30-year horizon",
        "10/20/30-वर्षीय horizon के साथ एक नामित capex scenario दर्ज करें",
        "10/20/30-वर्षांच्या horizon सह एक नामांकित capex scenario नोंदवा",
        "10/20/30-year horizon ke saath ek named capex scenario log karo",
    ),
    "planning-dashboard.steps.2.label": ("TCO / NPV Analysis", "TCO / NPV विश्लेषण", "TCO / NPV विश्लेषण", "TCO / NPV Analysis"),
    "planning-dashboard.steps.2.caption": (
        "Run cost-of-ownership and present-value analysis on it",
        "उस पर cost-of-ownership और present-value analysis चलाएँ",
        "त्यावर cost-of-ownership आणि present-value analysis चालवा",
        "Uspar cost-of-ownership aur present-value analysis run karo",
    ),
    "planning-dashboard.steps.3.label": ("Budget Impact", "Budget प्रभाव", "Budget परिणाम", "Budget Impact"),
    "planning-dashboard.steps.3.caption": (
        "Check the scenario against approved budgets",
        "scenario को approved budgets के विरुद्ध जाँचें",
        "scenario ला approved budgets विरुद्ध तपासा",
        "Scenario ko approved budgets ke against check karo",
    ),
    "planning-dashboard.steps.4.label": ("Capital Plan Registry", "Capital Plan Registry", "Capital Plan Registry", "Capital Plan Registry"),
    "planning-dashboard.steps.4.caption": (
        "Finalized scenarios land in the capital plan register",
        "अंतिम रूप से तय किए गए scenarios capital plan register में दर्ज हो जाते हैं",
        "अंतिम केलेले scenarios capital plan register मध्ये नोंदवले जातात",
        "Finalized scenarios capital plan register mein land ho jaate hain",
    ),
    "planning-dashboard.fieldRules.0.name": ("Scenario Name", "Scenario नाम", "Scenario नाव", "Scenario Name"),
    "planning-dashboard.fieldRules.0.description": (
        "Identifies the capex scenario; set on the Create Scenario screen, not here.",
        "capex scenario की पहचान करता है; इसे यहाँ नहीं, Create Scenario screen पर सेट किया जाता है।",
        "capex scenario ओळखतो; हे इथे नाही, Create Scenario screen वर सेट केले जाते.",
        "Capex scenario ko identify karta hai; ye yahan nahi, Create Scenario screen par set hota hai.",
    ),
    "planning-dashboard.fieldRules.1.name": ("Horizon (Years)", "Horizon (वर्ष)", "Horizon (वर्षे)", "Horizon (Years)"),
    "planning-dashboard.fieldRules.1.description": (
        "Planning horizon — 10, 20 or 30 years — that drives the NPV/TCO discounting.",
        "Planning horizon — 10, 20 या 30 वर्ष — जो NPV/TCO discounting को नियंत्रित करता है।",
        "Planning horizon — 10, 20 किंवा 30 वर्षे — जो NPV/TCO discounting ठरवतो.",
        "Planning horizon — 10, 20 ya 30 saal — jo NPV/TCO discounting ko drive karta hai.",
    ),
    "planning-dashboard.fieldRules.2.name": ("Description", "विवरण", "वर्णन", "Description"),
    "planning-dashboard.fieldRules.2.description": (
        "Optional free-text context; shows as — when left blank.",
        "वैकल्पिक free-text context; खाली छोड़ने पर — के रूप में दिखता है।",
        "पर्यायी free-text context; रिकामे सोडल्यास — असे दिसते.",
        "Optional free-text context; blank chhodne par — dikhta hai.",
    ),
    "planning-dashboard.tip.title": (
        "This page has no create form",
        "इस page पर कोई create form नहीं है",
        "या page वर कोणताही create form नाही",
        "Is page par koi create form nahi hai",
    ),
    "planning-dashboard.tip.body": (
        "\"New Scenario\", \"Create Scenario\" and \"View Capital Plan Registry\" all navigate away — none of them create or generate anything here. Scenarios are actually created on the Create Scenario page; this dashboard only lists what GET /investment/capex-scenarios already returns.",
        "\"New Scenario\", \"Create Scenario\" और \"View Capital Plan Registry\" — ये सभी दूसरे page पर ले जाते हैं, इनमें से कोई भी यहाँ कुछ create या generate नहीं करता। Scenarios वास्तव में Create Scenario page पर बनाए जाते हैं; यह dashboard केवल वही सूचीबद्ध करता है जो GET /investment/capex-scenarios पहले से लौटाता है।",
        "\"New Scenario\", \"Create Scenario\" आणि \"View Capital Plan Registry\" — हे सर्व दुसऱ्या page वर घेऊन जातात, यापैकी कोणतेही इथे काहीही create किंवा generate करत नाही. Scenarios प्रत्यक्षात Create Scenario page वर तयार केले जातात; हे dashboard फक्त तेच सूचीबद्ध करते जे GET /investment/capex-scenarios आधीच परत करते.",
        "\"New Scenario\", \"Create Scenario\" aur \"View Capital Plan Registry\" — ye sab dusre page par navigate kar dete hain, inme se koi bhi yahan kuch create ya generate nahi karta. Scenarios actually Create Scenario page par create hote hain; ye dashboard sirf wahi list karta hai jo GET /investment/capex-scenarios pehle se return karta hai.",
    ),
}


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 PLANNING_DASHBOARD.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(PLANNING_DASHBOARD)} planning-dashboard keys.")


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