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

Usage: docker compose exec api python seed_translations_pageinfo_capital_plan.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)
CAPITAL_PLAN = {
    "capital-plan.title": (
        "Capital Plan Registry",
        "कैपिटल प्लान रजिस्ट्री",
        "कॅपिटल प्लॅन रजिस्ट्री",
        "Capital Plan Registry",
    ),
    "capital-plan.subtitle": (
        "Long-range CapEx forecast scenarios",
        "दीर्घकालिक CapEx पूर्वानुमान scenarios",
        "दीर्घकालीन CapEx अंदाज scenarios",
        "Long-range CapEx forecast ke scenarios",
    ),
    "capital-plan.body.0": (
        "A capital plan is a named, long-horizon (10/20/30-year) CapEx forecast scenario — distinct from the per-asset repair-vs-replace scenarios used elsewhere in Investment Planning.",
        "एक capital plan एक नामित, दीर्घ-अवधि (10/20/30-वर्ष) CapEx पूर्वानुमान scenario है — जो Investment Planning में अन्यत्र उपयोग किए जाने वाले per-asset repair-vs-replace scenarios से अलग है।",
        "एक capital plan म्हणजे एक नामांकित, दीर्घ-कालावधीचा (10/20/30-वर्षांचा) CapEx अंदाज scenario आहे — जो Investment Planning मध्ये इतरत्र वापरल्या जाणाऱ्या per-asset repair-vs-replace scenarios पेक्षा वेगळा आहे.",
        "Ek capital plan ek named, long-horizon (10/20/30-year) CapEx forecast scenario hota hai — jo Investment Planning mein kahin aur use hone waale per-asset repair-vs-replace scenarios se alag hai.",
    ),
    "capital-plan.body.1": (
        "Use it to model organization-wide replacement/renewal spend over the plan's horizon before committing budget. Once created, a plan's name, horizon and description are the only fields stored here; detailed year-by-year projections are built from other investment-planning data.",
        "budget commit करने से पहले plan की horizon के दौरान organization-wide replacement/renewal खर्च को मॉडल करने के लिए इसका उपयोग करें। एक बार बन जाने पर, plan का नाम, horizon और description ही यहाँ संग्रहीत एकमात्र fields हैं; विस्तृत year-by-year projections अन्य investment-planning data से बनते हैं।",
        "budget commit करण्यापूर्वी plan च्या horizon दरम्यान organization-wide replacement/renewal खर्चाचे मॉडेलिंग करण्यासाठी याचा वापर करा. एकदा तयार झाल्यावर, plan चे नाव, horizon आणि description हीच येथे साठवलेली एकमेव fields आहेत; तपशीलवार year-by-year projections इतर investment-planning data वरून तयार होतात.",
        "Budget commit karne se pehle plan ki horizon ke dauran organization-wide replacement/renewal spend model karne ke liye ise use karein. Ek baar create hone ke baad, plan ka name, horizon aur description hi yahan stored fields hain; detailed year-by-year projections baaki investment-planning data se banti hain.",
    ),
    "capital-plan.stepsHeading": (
        "How a plan is built",
        "एक plan कैसे बनता है",
        "एक plan कसा तयार होतो",
        "Plan kaise banta hai",
    ),
    "capital-plan.steps.0.label": ("New Plan", "नया Plan", "नवीन Plan", "New Plan"),
    "capital-plan.steps.0.caption": (
        "Name it and pick a 10/20/30-year horizon.",
        "इसे नाम दें और 10/20/30-वर्ष की horizon चुनें।",
        "याला नाव द्या आणि 10/20/30-वर्षांची horizon निवडा.",
        "Isko naam dein aur 10/20/30-year ki horizon choose karein.",
    ),
    "capital-plan.steps.1.label": ("Describe", "विवरण", "वर्णन", "Describe"),
    "capital-plan.steps.1.caption": (
        "Optional description records intent/assumptions.",
        "वैकल्पिक description में intent/assumptions दर्ज होते हैं।",
        "पर्यायी description मध्ये intent/assumptions नोंदवले जातात.",
        "Optional description mein intent/assumptions record hote hain.",
    ),
    "capital-plan.steps.2.label": ("Create", "बनाएं", "तयार करा", "Create"),
    "capital-plan.steps.2.caption": (
        "Saved as a CapEx scenario and listed in the registry.",
        "CapEx scenario के रूप में save होता है और registry में सूचीबद्ध होता है।",
        "CapEx scenario म्हणून save होते आणि registry मध्ये सूचीबद्ध होते.",
        "CapEx scenario ke roop mein save hota hai aur registry mein list ho jaata hai.",
    ),
    "capital-plan.steps.3.label": ("Reference", "संदर्भ", "संदर्भ", "Reference"),
    "capital-plan.steps.3.caption": (
        "Used as a baseline elsewhere in Investment Planning.",
        "Investment Planning में अन्यत्र baseline के रूप में उपयोग होता है।",
        "Investment Planning मध्ये इतरत्र baseline म्हणून वापरले जाते.",
        "Investment Planning mein kahin aur baseline ke roop mein use hota hai.",
    ),
    "capital-plan.fieldRules.0.name": ("Name", "नाम", "नाव", "Name"),
    "capital-plan.fieldRules.0.description": (
        "Identifies the plan in the registry; the Create button stays disabled until this is filled in.",
        "registry में plan की पहचान करता है; जब तक यह भरा नहीं जाता, Create button disabled रहता है।",
        "registry मध्ये plan ची ओळख करतो; जोपर्यंत हे भरले जात नाही तोपर्यंत Create button disabled राहते.",
        "Registry mein plan ko identify karta hai; jab tak ye fill nahi hota, Create button disabled rehta hai.",
    ),
    "capital-plan.fieldRules.1.name": ("Horizon", "अवधि", "कालावधी", "Horizon"),
    "capital-plan.fieldRules.1.description": (
        "Forecast length — fixed to 10, 20 or 30 years; defaults to 10.",
        "पूर्वानुमान की लंबाई — 10, 20 या 30 वर्ष तक तय; डिफ़ॉल्ट 10 है।",
        "अंदाजाची लांबी — 10, 20 किंवा 30 वर्षांपर्यंत निश्चित; डिफॉल्ट 10 आहे.",
        "Forecast length — 10, 20 ya 30 years tak fixed; default 10 hai.",
    ),
    "capital-plan.fieldRules.2.name": ("Description", "विवरण", "वर्णन", "Description"),
    "capital-plan.fieldRules.2.description": (
        "Free-text notes on scope or assumptions; optional, shown as \"-\" in the table when empty.",
        "scope या assumptions पर free-text notes; वैकल्पिक, खाली होने पर table में \"-\" के रूप में दिखता है।",
        "scope किंवा assumptions वरील free-text notes; पर्यायी, रिकामे असल्यास table मध्ये \"-\" असे दिसते.",
        "Scope ya assumptions par free-text notes; optional hai, khaali hone par table mein \"-\" dikhta hai.",
    ),
    "capital-plan.tip.title": (
        "Don't confuse this with per-asset scenarios",
        "इसे per-asset scenarios के साथ भ्रमित न करें",
        "याला per-asset scenarios सोबत गोंधळून घेऊ नका",
        "Ise per-asset scenarios ke saath confuse mat karein",
    ),
    "capital-plan.tip.body": (
        "This registry holds long-range, plan-level CapEx forecasts only (name + horizon + notes). Repair-vs-replace analysis for individual assets lives under Create Scenario / Scenario Review — a plan created here does not automatically pull in or affect those asset-level scenarios.",
        "यह registry केवल दीर्घकालिक, plan-level CapEx forecasts (name + horizon + notes) रखती है। individual assets के लिए repair-vs-replace विश्लेषण Create Scenario / Scenario Review के अंतर्गत होता है — यहाँ बनाया गया plan उन asset-level scenarios को स्वतः शामिल या प्रभावित नहीं करता।",
        "ही registry फक्त दीर्घकालीन, plan-level CapEx forecasts (name + horizon + notes) साठवते. वैयक्तिक assets साठी repair-vs-replace विश्लेषण Create Scenario / Scenario Review अंतर्गत असते — येथे तयार केलेला plan त्या asset-level scenarios ला आपोआप समाविष्ट किंवा प्रभावित करत नाही.",
        "Ye registry sirf long-range, plan-level CapEx forecasts (name + horizon + notes) rakhti hai. Individual assets ke liye repair-vs-replace analysis Create Scenario / Scenario Review ke under hota hai — yahan banaya gaya plan un asset-level scenarios ko automatically pull ya affect nahi karta.",
    ),
}


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 CAPITAL_PLAN.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(CAPITAL_PLAN)} capital-plan keys.")


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