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

Usage: docker compose exec api python seed_translations_pageinfo_reports.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)
REPORTS = {
    "reports.title": (
        "AAMS General Reports & Analytics",
        "AAMS सामान्य रिपोर्ट और एनालिटिक्स",
        "AAMS सामान्य अहवाल आणि विश्लेषण",
        "AAMS General Reports & Analytics",
    ),
    "reports.subtitle": (
        "CFO dashboard KPIs and the live asset register, in one view",
        "CFO डैशबोर्ड के KPIs और लाइव asset register, एक ही व्यू में",
        "CFO डॅशबोर्ड चे KPIs आणि लाइव्ह asset register, एकाच व्ह्यूमध्ये",
        "CFO dashboard ke KPIs aur live asset register, ek hi view mein",
    ),
    "reports.body.0": (
        "This page pulls two things live: the financial KPI summary (accumulated depreciation, insurance coverage, ITC claimed, budget utilisation, NBV by asset class) and the latest rows from the asset register.",
        "यह पेज दो चीज़ें लाइव खींचता है: financial KPI सारांश (accumulated depreciation, insurance coverage, ITC claimed, budget utilisation, asset class के अनुसार NBV) और asset register की नवीनतम rows।",
        "हे पेज दोन गोष्टी लाइव्ह आणते: financial KPI सारांश (accumulated depreciation, insurance coverage, ITC claimed, budget utilisation, asset class नुसार NBV) आणि asset register मधील नवीनतम rows.",
        "Ye page do cheezein live pull karta hai: financial KPI summary (accumulated depreciation, insurance coverage, ITC claimed, budget utilisation, asset class ke hisaab se NBV) aur asset register ki latest rows.",
    ),
    "reports.body.1": (
        "The two blocks load independently — a role that can see the KPIs but not the register (or vice versa) still gets a usable page instead of a blank one.",
        "दोनों blocks स्वतंत्र रूप से लोड होते हैं — जो role KPIs देख सकता है लेकिन register नहीं (या इसके विपरीत), उसे भी खाली पेज के बजाय एक उपयोगी पेज मिलता है।",
        "दोन्ही blocks स्वतंत्रपणे लोड होतात — जो role KPIs पाहू शकतो पण register नाही (किंवा उलट), त्यालाही रिकाम्या पेजऐवजी उपयुक्त पेज मिळते.",
        "Dono blocks independently load hote hain — jo role KPIs dekh sakta hai lekin register nahi (ya ulta), usko bhi blank page ke bajaye ek usable page milta hai.",
    ),
    "reports.stepsHeading": (
        "How the page loads",
        "पेज कैसे लोड होता है",
        "पेज कसे लोड होते",
        "Page kaise load hota hai",
    ),
    "reports.steps.0.label": ("Fetch KPIs", "KPIs फ़ेच करें", "KPIs फेच करा", "KPIs Fetch Karna"),
    "reports.steps.0.caption": (
        "CFO dashboard summary (needs cfo_dashboard:view).",
        "CFO डैशबोर्ड सारांश (cfo_dashboard:view चाहिए)।",
        "CFO डॅशबोर्ड सारांश (cfo_dashboard:view आवश्यक).",
        "CFO dashboard summary (cfo_dashboard:view chahiye).",
    ),
    "reports.steps.1.label": ("Fetch Register", "रजिस्टर फ़ेच करें", "रजिस्टर फेच करा", "Register Fetch Karna"),
    "reports.steps.1.caption": (
        "Latest 10 assets from /reports/asset-list.",
        "/reports/asset-list से नवीनतम 10 assets।",
        "/reports/asset-list मधून नवीनतम 10 assets.",
        "/reports/asset-list se latest 10 assets.",
    ),
    "reports.steps.2.label": ("Review", "समीक्षा", "पुनरावलोकन", "Review Karna"),
    "reports.steps.2.caption": (
        "Scan KPI cards and the NBV-by-class chart.",
        "KPI cards और NBV-by-class chart को स्कैन करें।",
        "KPI cards आणि NBV-by-class chart स्कॅन करा.",
        "KPI cards aur NBV-by-class chart ko scan karein.",
    ),
    "reports.steps.3.label": ("Export", "एक्सपोर्ट", "एक्सपोर्ट", "Export Karna"),
    "reports.steps.3.caption": (
        "Download the asset table as CSV.",
        "Asset table को CSV के रूप में डाउनलोड करें।",
        "Asset table CSV स्वरूपात डाउनलोड करा.",
        "Asset table ko CSV format mein download karein.",
    ),
    "reports.fieldRules.0.name": (
        "Net Book Value by Class",
        "Asset Class के अनुसार Net Book Value",
        "Asset Class नुसार Net Book Value",
        "Asset Class ke hisaab se Net Book Value",
    ),
    "reports.fieldRules.0.description": (
        "Donut chart of current in-operation asset value split by asset class; segments sum to Total NBV in the center.",
        "वर्तमान in-operation asset value का donut chart, asset class के अनुसार विभाजित; segments केंद्र में Total NBV के बराबर जुड़ते हैं।",
        "सध्याच्या in-operation asset value चा donut chart, asset class नुसार विभागलेला; segments मध्यभागी असलेल्या Total NBV इतके बेरीज होतात.",
        "Current in-operation asset value ka donut chart, asset class ke hisaab se split; segments center mein Total NBV ke barabar sum hote hain.",
    ),
    "reports.fieldRules.1.name": ("Budget Utilisation", "बजट उपयोग", "बजेट वापर", "Budget Utilisation"),
    "reports.fieldRules.1.description": (
        "Percentage of allocated budget spent so far, paired with the count of assets pending commissioning.",
        "अब तक खर्च किए गए allocated budget का प्रतिशत, commissioning के लिए pending assets की संख्या के साथ।",
        "आतापर्यंत खर्च झालेल्या allocated budget ची टक्केवारी, commissioning साठी pending असलेल्या assets च्या संख्येसह.",
        "Ab tak spend hue allocated budget ka percentage, commissioning ke liye pending assets ki count ke saath.",
    ),
    "reports.fieldRules.2.name": ("Lifecycle State", "लाइफसाइकिल स्थिति", "लाइफसायकल स्थिती", "Lifecycle State"),
    "reports.fieldRules.2.description": (
        "Current status of each asset in the register (e.g. in_operation, retired) — read-only here.",
        "register में प्रत्येक asset की वर्तमान स्थिति (जैसे in_operation, retired) — यहाँ केवल read-only है।",
        "register मधील प्रत्येक asset ची सद्यस्थिती (उदा. in_operation, retired) — येथे फक्त read-only आहे.",
        "Register mein har asset ka current status (jaise in_operation, retired) — yahan sirf read-only hai.",
    ),
    "reports.fieldRules.3.name": ("Acquisition Cost", "अधिग्रहण लागत", "संपादन खर्च", "Acquisition Cost"),
    "reports.fieldRules.3.description": (
        "Original booked cost of the asset; shows — when not recorded.",
        "Asset की मूल booked लागत; रिकॉर्ड न होने पर — दिखाता है।",
        "Asset ची मूळ booked किंमत; रेकॉर्ड नसल्यास — दाखवते.",
        "Asset ki original booked cost; record na hone par — dikhata hai.",
    ),
    "reports.tip.title": (
        "Blank KPI block isn't a bug",
        "खाली KPI ब्लॉक कोई बग नहीं है",
        "रिकामा KPI ब्लॉक ही बग नाही",
        "Blank KPI block koi bug nahi hai",
    ),
    "reports.tip.body": (
        "The KPI summary needs a stricter permission (cfo_dashboard:view) than the asset register (report:view). If your role only has the latter — e.g. Auditor — you'll see the register table with a message instead of the KPI cards; that's expected, not a load failure.",
        "KPI सारांश के लिए asset register (report:view) की तुलना में सख्त permission (cfo_dashboard:view) चाहिए। अगर आपके role के पास केवल बाद वाली permission है — जैसे Auditor — तो आपको KPI cards के बजाय एक संदेश के साथ register table दिखेगी; यह अपेक्षित है, कोई load failure नहीं।",
        "KPI सारांशासाठी asset register (report:view) पेक्षा अधिक कडक permission (cfo_dashboard:view) आवश्यक आहे. जर तुमच्या role कडे फक्त नंतरची permission असेल — उदा. Auditor — तर तुम्हाला KPI cards ऐवजी एका संदेशासह register table दिसेल; हे अपेक्षित आहे, load failure नाही.",
        "KPI summary ko asset register (report:view) se zyada strict permission (cfo_dashboard:view) chahiye. Agar aapke role ke paas sirf baad wali permission hai — jaise Auditor — to aapko KPI cards ki jagah ek message ke saath register table dikhega; ye expected hai, load failure nahi.",
    ),
}


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 REPORTS.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(REPORTS)} reports keys.")


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