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

Usage: docker compose exec api python seed_translations_pageinfo_advanced_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)
ADVANCED_REPORTS = {
    "advanced-reports.title": (
        "Advanced Standard Reports",
        "एडवांस्ड स्टैंडर्ड रिपोर्ट्स",
        "अ‍ॅडव्हान्स्ड स्टँडर्ड रिपोर्ट्स",
        "Advanced Standard Reports",
    ),
    "advanced-reports.subtitle": (
        "Compliance & oversight reports, plus live BI feeds",
        "अनुपालन और निगरानी रिपोर्ट्स, साथ ही लाइव BI फ़ीड",
        "अनुपालन आणि देखरेख अहवाल, तसेच लाइव्ह BI फीड्स",
        "Compliance aur oversight reports, plus live BI feeds",
    ),
    "advanced-reports.body.0": (
        "Four independent reports live under one page: custodian exceptions (accountability gaps), warranty exposure (upcoming expiries), asset transfer history (custody audit trail), and OData feeds (live links for Excel/Power BI).",
        "एक ही पेज पर चार स्वतंत्र रिपोर्ट्स मौजूद हैं: custodian exceptions (जवाबदेही में कमियाँ), warranty exposure (आने वाली expiries), asset transfer history (custody का audit trail), और OData feeds (Excel/Power BI के लिए live links)।",
        "एकाच पेजवर चार स्वतंत्र अहवाल आहेत: custodian exceptions (जबाबदारीतील त्रुटी), warranty exposure (येणाऱ्या expiries), asset transfer history (custody चा audit trail), आणि OData feeds (Excel/Power BI साठी live links).",
        "Ek hi page par four independent reports hain: custodian exceptions (accountability ki gaps), warranty exposure (aane wali expiries), asset transfer history (custody ka audit trail), aur OData feeds (Excel/Power BI ke liye live links).",
    ),
    "advanced-reports.body.1": (
        "Each tab loads its own data on demand — switching tabs doesn't reload the others, and a failure in one report doesn't affect the rest.",
        "हर tab अपना डेटा ज़रूरत पड़ने पर लोड करता है — tabs बदलने से बाकी tabs रीलोड नहीं होते, और किसी एक रिपोर्ट में विफलता बाकी रिपोर्ट्स को प्रभावित नहीं करती।",
        "प्रत्येक tab आवश्यकतेनुसार स्वतःचा डेटा लोड करते — tabs बदलल्याने इतर tabs रीलोड होत नाहीत, आणि एका अहवालातील अपयश इतरांवर परिणाम करत नाही.",
        "Har tab apna data zaroorat padne par load karta hai — tabs switch karne se baaki tabs reload nahi hote, aur ek report mein failure baaki reports ko affect nahi karta.",
    ),
    "advanced-reports.stepsHeading": (
        "The four tabs",
        "चारों tabs",
        "चारही tabs",
        "Ye chaar tabs",
    ),
    "advanced-reports.steps.0.label": ("Custodian Exceptions", "Custodian Exceptions", "Custodian Exceptions", "Custodian Exceptions"),
    "advanced-reports.steps.0.caption": (
        "In-use assets with no custodian, or one never acknowledged.",
        "उपयोग में मौजूद ऐसे assets जिनका कोई custodian नहीं है, या जिसने कभी acknowledge नहीं किया।",
        "वापरात असलेल्या अशा assets ज्यांना custodian नाही, किंवा ज्याने कधीच acknowledge केले नाही.",
        "In-use assets jinka koi custodian nahi hai, ya jisne kabhi acknowledge nahi kiya.",
    ),
    "advanced-reports.steps.1.label": ("Warranty Exposure", "Warranty Exposure", "Warranty Exposure", "Warranty Exposure"),
    "advanced-reports.steps.1.caption": (
        "Highest-value assets expiring within a chosen window.",
        "चुनी गई window के भीतर expire होने वाले सबसे अधिक मूल्य के assets।",
        "निवडलेल्या window मध्ये expire होणाऱ्या सर्वाधिक मूल्याच्या assets.",
        "Chuni gayi window ke andar expire hone wale sabse zyada value ke assets.",
    ),
    "advanced-reports.steps.2.label": ("Transfer History", "Transfer History", "Transfer History", "Transfer History"),
    "advanced-reports.steps.2.caption": (
        "Every custody handoff, filterable by date range.",
        "हर custody handoff, जिसे date range के आधार पर filter किया जा सकता है।",
        "प्रत्येक custody handoff, जो date range नुसार filter करता येते.",
        "Har custody handoff, jise date range ke basis par filter kiya ja sakta hai.",
    ),
    "advanced-reports.steps.3.label": ("OData Feeds", "OData Feeds", "OData Feeds", "OData Feeds"),
    "advanced-reports.steps.3.caption": (
        "Copyable live URLs for Excel/Power BI, with a 5-row preview.",
        "Excel/Power BI के लिए copy किए जा सकने वाले live URLs, साथ में 5-row का preview।",
        "Excel/Power BI साठी copy करता येणारे live URLs, सोबत 5-row चा preview.",
        "Excel/Power BI ke liye copy kiye ja sakne wale live URLs, saath mein 5-row ka preview.",
    ),
    "advanced-reports.fieldRules.0.name": ("Exception Type", "Exception Type", "Exception Type", "Exception Type"),
    "advanced-reports.fieldRules.0.description": (
        "No Custodian vs Not Acknowledged — the two ways an in-use asset can lack an accepted owner.",
        "No Custodian बनाम Not Acknowledged — ये दो तरीके हैं जिनसे किसी in-use asset का कोई accepted owner नहीं हो सकता।",
        "No Custodian विरुद्ध Not Acknowledged — हे दोन मार्ग आहेत ज्याद्वारे एखाद्या in-use asset ला accepted owner नसू शकतो.",
        "No Custodian vs Not Acknowledged — ye do tareeke hain jinse kisi in-use asset ka koi accepted owner nahi ho sakta.",
    ),
    "advanced-reports.fieldRules.1.name": ("Window", "Window", "Window", "Window"),
    "advanced-reports.fieldRules.1.description": (
        "Warranty Exposure only: 30/60/90/180-day lookahead; changing it re-fetches the report.",
        "केवल Warranty Exposure के लिए: 30/60/90/180-दिन का lookahead; इसे बदलने पर रिपोर्ट फिर से fetch होती है।",
        "फक्त Warranty Exposure साठी: 30/60/90/180-दिवसांचा lookahead; तो बदलल्यास अहवाल पुन्हा fetch होतो.",
        "Sirf Warranty Exposure ke liye: 30/60/90/180-din ka lookahead; ise change karne par report dobara fetch hoti hai.",
    ),
    "advanced-reports.fieldRules.2.name": ("From / To Date", "From / To Date", "From / To Date", "From / To Date"),
    "advanced-reports.fieldRules.2.description": (
        "Transfer History only: restricts the audit trail to transfers effective in this range; click Filter to apply.",
        "केवल Transfer History के लिए: audit trail को इस range में प्रभावी transfers तक सीमित करता है; लागू करने के लिए Filter पर क्लिक करें।",
        "फक्त Transfer History साठी: audit trail ला या range मध्ये प्रभावी असलेल्या transfers पुरते मर्यादित करते; लागू करण्यासाठी Filter वर क्लिक करा.",
        "Sirf Transfer History ke liye: audit trail ko is range mein effective transfers tak restrict karta hai; apply karne ke liye Filter par click karein.",
    ),
    "advanced-reports.fieldRules.3.name": ("Feed URL", "Feed URL", "Feed URL", "Feed URL"),
    "advanced-reports.fieldRules.3.description": (
        "OData Feeds only: the copied link points at the API host on port 8000, not the web app's own origin.",
        "केवल OData Feeds के लिए: copy किया गया link web app के अपने origin पर नहीं, बल्कि port 8000 पर मौजूद API host पर pointing करता है।",
        "फक्त OData Feeds साठी: copy केलेली link वेब अ‍ॅपच्या स्वतःच्या origin वर नाही, तर port 8000 वरील API host वर point करते.",
        "Sirf OData Feeds ke liye: copy kiya gaya link web app ke apne origin par nahi, balki port 8000 par mojood API host par point karta hai.",
    ),
    "advanced-reports.tip.title": (
        "Preview before you share a feed link",
        "feed link शेयर करने से पहले Preview करें",
        "feed link शेअर करण्यापूर्वी Preview करा",
        "Feed link share karne se pehle Preview karein",
    ),
    "advanced-reports.tip.body": (
        "OData URLs are copied as raw links, not validated against your permissions at copy time — always hit Preview first to confirm the columns and row count look right before pasting the link into Excel or Power BI.",
        "OData URLs को raw links के रूप में copy किया जाता है, copy करते समय आपकी permissions के विरुद्ध validate नहीं किया जाता — link को Excel या Power BI में paste करने से पहले हमेशा Preview पर क्लिक करके पुष्टि करें कि columns और row count सही दिख रहे हैं।",
        "OData URLs raw links म्हणून copy केल्या जातात, copy करताना तुमच्या permissions विरुद्ध validate केल्या जात नाहीत — link Excel किंवा Power BI मध्ये paste करण्यापूर्वी नेहमी Preview वर क्लिक करून खात्री करा की columns आणि row count बरोबर दिसत आहेत.",
        "OData URLs raw links ke tarah copy hote hain, copy karte time aapki permissions ke against validate nahi hote — link ko Excel ya Power BI mein paste karne se pehle hamesha Preview hit karke confirm karein ki columns aur row count sahi dikh rahe 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 ADVANCED_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(ADVANCED_REPORTS)} advanced-reports keys.")


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