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

Usage: docker compose exec api python seed_translations_pageinfo_reports_analytics.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_ANALYTICS = {
    "reports-analytics.title": (
        "AAMS Reports & Analytics",
        "AAMS रिपोर्ट्स और एनालिटिक्स",
        "AAMS रिपोर्ट्स आणि अॅनालिटिक्स",
        "AAMS Reports & Analytics",
    ),
    "reports-analytics.subtitle": (
        "Run standard reports, monitor KPIs, build ad-hoc reports, and automate recurring exports.",
        "Standard reports चलाएं, KPIs मॉनिटर करें, ad-hoc reports बनाएं, और recurring exports को automate करें।",
        "Standard reports चालवा, KPIs मॉनिटर करा, ad-hoc reports तयार करा, आणि recurring exports automate करा.",
        "Standard reports run karein, KPIs monitor karein, ad-hoc reports banayein, aur recurring exports ko automate karein.",
    ),
    "reports-analytics.body.0": (
        "This dashboard is the entry point for all reporting: pick a standard report to view and export it, check live KPI analytics, or assemble your own filtered report. You can also schedule any report type for automatic recurring delivery.",
        "यह dashboard सभी reporting का entry point है: कोई standard report चुनकर देखें और export करें, live KPI analytics जांचें, या अपनी खुद की filtered report तैयार करें। आप किसी भी report type को automatic recurring delivery के लिए schedule भी कर सकते हैं।",
        "हे dashboard सर्व reporting साठी entry point आहे: एखादी standard report निवडून पहा आणि export करा, live KPI analytics तपासा, किंवा तुमची स्वतःची filtered report तयार करा. तुम्ही कोणत्याही report type साठी automatic recurring delivery चे schedule देखील करू शकता.",
        "Ye dashboard sabhi reporting ka entry point hai: koi standard report select karke dekhein aur export karein, live KPI analytics check karein, ya apni khud ki filtered report banayein. Aap kisi bhi report type ko automatic recurring delivery ke liye schedule bhi kar sakte hain.",
    ),
    "reports-analytics.stepsHeading": (
        "How this dashboard flows",
        "यह dashboard कैसे काम करता है",
        "हे dashboard कसे कार्य करते",
        "Ye dashboard kaise flow karta hai",
    ),
    "reports-analytics.steps.0.label": (
        "Standard Reports",
        "स्टैंडर्ड Reports",
        "स्टँडर्ड Reports",
        "Standard Reports",
    ),
    "reports-analytics.steps.0.caption": (
        "Click a report card (Asset List, Depreciation, Idle, Uncustodied) to fetch it.",
        "इसे fetch करने के लिए किसी report card (Asset List, Depreciation, Idle, Uncustodied) पर क्लिक करें।",
        "ते fetch करण्यासाठी एखाद्या report card (Asset List, Depreciation, Idle, Uncustodied) वर क्लिक करा.",
        "Isse fetch karne ke liye kisi report card (Asset List, Depreciation, Idle, Uncustodied) par click karein.",
    ),
    "reports-analytics.steps.1.label": (
        "View & Export",
        "देखें और Export करें",
        "पहा आणि Export करा",
        "View & Export",
    ),
    "reports-analytics.steps.1.caption": (
        "Browse the result table, export to CSV, or close it to pick another report.",
        "result table ब्राउज़ करें, CSV में export करें, या किसी दूसरी report चुनने के लिए इसे बंद करें।",
        "result table ब्राउझ करा, CSV मध्ये export करा, किंवा दुसरी report निवडण्यासाठी ते बंद करा.",
        "Result table browse karein, CSV mein export karein, ya doosri report choose karne ke liye ise band karein.",
    ),
    "reports-analytics.steps.2.label": (
        "KPI Analytics",
        "KPI एनालिटिक्स",
        "KPI अॅनालिटिक्स",
        "KPI Analytics",
    ),
    "reports-analytics.steps.2.caption": (
        "Live depreciation, insurance coverage, ITC and budget utilisation metrics.",
        "Live depreciation, insurance coverage, ITC और budget utilisation के metrics।",
        "Live depreciation, insurance coverage, ITC आणि budget utilisation चे metrics.",
        "Live depreciation, insurance coverage, ITC aur budget utilisation ke metrics.",
    ),
    "reports-analytics.steps.3.label": (
        "Custom & Schedule",
        "Custom और Schedule",
        "Custom आणि Schedule",
        "Custom & Schedule",
    ),
    "reports-analytics.steps.3.caption": (
        "Filter an ad-hoc report, or automate any report type on a recurring schedule.",
        "किसी ad-hoc report को फ़िल्टर करें, या किसी भी report type को recurring schedule पर automate करें।",
        "एखादी ad-hoc report फिल्टर करा, किंवा कोणत्याही report type ला recurring schedule वर automate करा.",
        "Kisi ad-hoc report ko filter karein, ya kisi bhi report type ko recurring schedule par automate karein.",
    ),
    "reports-analytics.fieldRules.0.name": (
        "Report Type",
        "रिपोर्ट टाइप",
        "रिपोर्ट टाइप",
        "Report Type",
    ),
    "reports-analytics.fieldRules.0.description": (
        "Which report is generated on schedule (CFO/Auditor Dashboard, CAG Pack, Depreciation, Budget Variance); required before Create Schedule enables.",
        "यह तय करता है कि schedule पर कौन-सी report generate होगी (CFO/Auditor Dashboard, CAG Pack, Depreciation, Budget Variance); Create Schedule enable होने से पहले यह ज़रूरी है।",
        "हे ठरवते की schedule वर कोणती report generate होईल (CFO/Auditor Dashboard, CAG Pack, Depreciation, Budget Variance); Create Schedule enable होण्यापूर्वी हे आवश्यक आहे.",
        "Ye decide karta hai ki schedule par kaunsi report generate hogi (CFO/Auditor Dashboard, CAG Pack, Depreciation, Budget Variance); Create Schedule enable hone se pehle ye zaroori hai.",
    ),
    "reports-analytics.fieldRules.1.name": (
        "Frequency",
        "फ़्रीक्वेंसी",
        "फ्रिक्वेन्सी",
        "Frequency",
    ),
    "reports-analytics.fieldRules.1.description": (
        "How often the scheduled report regenerates: Daily, Weekly or Monthly.",
        "scheduled report कितनी बार regenerate होती है: Daily, Weekly या Monthly।",
        "scheduled report किती वेळा regenerate होते: Daily, Weekly किंवा Monthly.",
        "Scheduled report kitni baar regenerate hoti hai: Daily, Weekly ya Monthly.",
    ),
    "reports-analytics.fieldRules.2.name": (
        "Format",
        "फॉर्मेट",
        "फॉरमॅट",
        "Format",
    ),
    "reports-analytics.fieldRules.2.description": (
        "Output file type for the scheduled export: CSV, PDF or XLSX.",
        "scheduled export के लिए output file type: CSV, PDF या XLSX।",
        "scheduled export साठी output file type: CSV, PDF किंवा XLSX.",
        "Scheduled export ke liye output file type: CSV, PDF ya XLSX.",
    ),
    "reports-analytics.fieldRules.3.name": (
        "Asset Type",
        "एसेट टाइप",
        "असेट टाइप",
        "Asset Type",
    ),
    "reports-analytics.fieldRules.3.description": (
        "Optional filter narrowing the custom report to one asset class; leave blank to include all types.",
        "एक optional filter जो custom report को एक asset class तक सीमित करता है; सभी types शामिल करने के लिए इसे खाली छोड़ें।",
        "एक optional filter जो custom report ला एका asset class पुरती मर्यादित करतो; सर्व types समाविष्ट करण्यासाठी हे रिकामे ठेवा.",
        "Ek optional filter jo custom report ko ek asset class tak limit karta hai; sabhi types include karne ke liye ise blank chhod dein.",
    ),
    "reports-analytics.fieldRules.4.name": (
        "Email (optional)",
        "ईमेल (वैकल्पिक)",
        "ईमेल (पर्यायी)",
        "Email (optional)",
    ),
    "reports-analytics.fieldRules.4.description": (
        "Comma-separated email addresses to receive each scheduled export; leave blank if no email delivery is needed.",
        "हर scheduled export प्राप्त करने के लिए comma-separated email addresses; अगर email delivery की ज़रूरत नहीं है तो इसे खाली छोड़ें।",
        "प्रत्येक scheduled export प्राप्त करण्यासाठी comma-separated email addresses; email delivery आवश्यक नसल्यास हे रिकामे ठेवा.",
        "Har scheduled export receive karne ke liye comma-separated email addresses; agar email delivery ki zaroorat nahi hai to ise blank chhod dein.",
    ),
    "reports-analytics.tip.title": (
        "Custom Report columns are fixed",
        "Custom Report के columns fixed हैं",
        "Custom Report चे columns fixed आहेत",
        "Custom Report ke columns fixed hain",
    ),
    "reports-analytics.tip.body": (
        "The Custom Report Builder only filters by Asset Type, Date Range and Location — the output columns (ID, Name, Asset Class, Location, Acquisition Cost) are hardcoded, there's no field picker here. Use Report Builder (Reports → Report Builder) if you need different columns.",
        "Custom Report Builder केवल Asset Type, Date Range और Location से फ़िल्टर करता है — output columns (ID, Name, Asset Class, Location, Acquisition Cost) hardcoded हैं, यहाँ कोई field picker नहीं है। अलग columns चाहिए तो Report Builder (Reports → Report Builder) का उपयोग करें।",
        "Custom Report Builder फक्त Asset Type, Date Range आणि Location वर filter करतो — output columns (ID, Name, Asset Class, Location, Acquisition Cost) hardcoded आहेत, इथे field picker नाही. वेगळे columns हवे असल्यास Report Builder (Reports → Report Builder) वापरा.",
        "Custom Report Builder sirf Asset Type, Date Range aur Location se filter karta hai — output columns (ID, Name, Asset Class, Location, Acquisition Cost) hardcoded hain, yahan koi field picker nahi hai. Alag columns chahiye to Report Builder (Reports → Report Builder) use karein.",
    ),
}


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_ANALYTICS.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_ANALYTICS)} reports-analytics keys.")


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