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

Usage: docker compose exec api python seed_translations_pageinfo_scheduled_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)
SCHEDULED_REPORTS = {
    "scheduled-reports.title": (
        "Scheduled Reports",
        "शेड्यूल्ड रिपोर्ट्स",
        "शेड्यूल्ड रिपोर्ट्स",
        "Scheduled Reports",
    ),
    "scheduled-reports.subtitle": (
        "Automated, recurring delivery of a fixed report to a mailing list.",
        "एक तय रिपोर्ट की मेलिंग लिस्ट को ऑटोमेटेड, आवर्ती डिलीवरी।",
        "निश्चित रिपोर्टची मेलिंग लिस्टला ऑटोमेटेड, आवर्ती डिलिव्हरी.",
        "Ek fixed report ki mailing list ko automated, recurring delivery.",
    ),
    "scheduled-reports.body.0": (
        "Each schedule ties one of the platform's fixed report types (CFO Dashboard, Auditor Dashboard, CAG Pack, Depreciation, Budget Variance) to a frequency and a list of recipient emails.",
        "हर schedule platform के fixed report types (CFO Dashboard, Auditor Dashboard, CAG Pack, Depreciation, Budget Variance) में से किसी एक को एक frequency और recipient emails की लिस्ट से जोड़ता है।",
        "प्रत्येक schedule platform च्या fixed report types (CFO Dashboard, Auditor Dashboard, CAG Pack, Depreciation, Budget Variance) पैकी एकाला frequency आणि recipient emails च्या यादीशी जोडते.",
        "Har schedule platform ke fixed report types (CFO Dashboard, Auditor Dashboard, CAG Pack, Depreciation, Budget Variance) mein se ek ko ek frequency aur recipient emails ki list ke saath link karta hai.",
    ),
    "scheduled-reports.body.1": (
        "There is no custom report name or arbitrary export layout here — for a self-built report, use Report Builder first, then schedule the saved layout from there.",
        "यहाँ कोई custom report name या मनमाना export layout नहीं है — अपनी बनाई हुई report के लिए पहले Report Builder इस्तेमाल करें, फिर वहाँ से saved layout को schedule करें।",
        "इथे कोणतेही custom report name किंवा मनमानी export layout नाही — स्वतः तयार केलेल्या report साठी आधी Report Builder वापरा, नंतर तिथून saved layout schedule करा.",
        "Yahan koi custom report name ya arbitrary export layout nahi hota — khud banayi hui report ke liye pehle Report Builder use karein, phir wahan se saved layout ko schedule karein.",
    ),
    "scheduled-reports.stepsHeading": (
        "Schedule lifecycle",
        "शेड्यूल जीवनचक्र",
        "शेड्यूल जीवनचक्र",
        "Schedule ka lifecycle",
    ),
    "scheduled-reports.steps.0.label": (
        "Create Schedule",
        "शेड्यूल बनाएं",
        "शेड्यूल तयार करा",
        "Schedule Create Karein",
    ),
    "scheduled-reports.steps.0.caption": (
        "Pick report type, frequency, recipients and format.",
        "report type, frequency, recipients और format चुनें।",
        "report type, frequency, recipients आणि format निवडा.",
        "Report type, frequency, recipients aur format select karein.",
    ),
    "scheduled-reports.steps.1.label": (
        "Active",
        "सक्रिय",
        "सक्रिय",
        "Active",
    ),
    "scheduled-reports.steps.1.caption": (
        "Runs automatically on the chosen cadence; Next Run updates each cycle.",
        "चुनी गई cadence पर automatically चलता है; हर cycle में Next Run अपडेट होता है।",
        "निवडलेल्या cadence वर automatically चालते; प्रत्येक cycle मध्ये Next Run अपडेट होते.",
        "Chuni gayi cadence par automatically chalta hai; har cycle mein Next Run update hota hai.",
    ),
    "scheduled-reports.steps.2.label": (
        "Delivered",
        "डिलीवर हुआ",
        "डिलिव्हर झाले",
        "Delivered",
    ),
    "scheduled-reports.steps.2.caption": (
        "The report is emailed to all recipients in the selected file format.",
        "report चुने गए file format में सभी recipients को email कर दी जाती है।",
        "निवडलेल्या file format मध्ये report सर्व recipients ना email केली जाते.",
        "Report selected file format mein sabhi recipients ko email ho jaati hai.",
    ),
    "scheduled-reports.steps.3.label": (
        "Paused / Deleted",
        "रोका गया / हटाया गया",
        "थांबवले / हटवले",
        "Paused / Deleted",
    ),
    "scheduled-reports.steps.3.caption": (
        "Toggle off to stop runs without losing config, or delete to remove it entirely.",
        "config खोए बिना runs रोकने के लिए toggle off करें, या इसे पूरी तरह हटाने के लिए delete करें।",
        "config न गमावता runs थांबवण्यासाठी toggle off करा, किंवा पूर्णपणे काढण्यासाठी delete करा.",
        "Config lose kiye bina runs rokne ke liye toggle off karein, ya poori tarah remove karne ke liye delete karein.",
    ),
    "scheduled-reports.fieldRules.0.name": (
        "Report Type",
        "रिपोर्ट प्रकार",
        "रिपोर्ट प्रकार",
        "Report Type",
    ),
    "scheduled-reports.fieldRules.0.description": (
        "Fixed backend report to run — not a free-text or custom-built name.",
        "चलाई जाने वाली एक fixed backend report — यह free-text या custom-built नाम नहीं है।",
        "चालवायची एक fixed backend report — हे free-text किंवा custom-built नाव नाही.",
        "Ek fixed backend report jo run hoti hai — ye free-text ya custom-built naam nahi hai.",
    ),
    "scheduled-reports.fieldRules.1.name": (
        "Frequency",
        "फ्रीक्वेंसी",
        "फ्रिक्वेन्सी",
        "Frequency",
    ),
    "scheduled-reports.fieldRules.1.description": (
        "Daily, weekly or monthly cadence; sets the Next Run date shown in the table.",
        "Daily, weekly या monthly cadence; table में दिखने वाली Next Run date इसी से तय होती है।",
        "Daily, weekly किंवा monthly cadence; table मध्ये दिसणारी Next Run date यावरून ठरते.",
        "Daily, weekly ya monthly cadence; table mein dikhne wali Next Run date isi se set hoti hai.",
    ),
    "scheduled-reports.fieldRules.2.name": (
        "Recipients",
        "प्राप्तकर्ता",
        "प्राप्तकर्ते",
        "Recipients",
    ),
    "scheduled-reports.fieldRules.2.description": (
        "Comma-separated emails; only checked for at least one non-empty entry, not email format.",
        "कॉमा से अलग किए गए emails; केवल यह जांचा जाता है कि कम से कम एक non-empty entry हो, email format नहीं।",
        "कॉमाने वेगळे केलेले emails; फक्त किमान एक non-empty entry आहे का हे तपासले जाते, email format नाही.",
        "Comma se separate emails; sirf ye check hota hai ki kam se kam ek non-empty entry ho, email format nahi.",
    ),
    "scheduled-reports.fieldRules.3.name": (
        "Format",
        "फॉर्मेट",
        "फॉरमॅट",
        "Format",
    ),
    "scheduled-reports.fieldRules.3.description": (
        "XLSX, CSV or PDF file recipients receive by email; defaults to XLSX.",
        "XLSX, CSV या PDF file recipients को email से मिलती है; default XLSX होता है।",
        "XLSX, CSV किंवा PDF file recipients ना email द्वारे मिळते; default XLSX असते.",
        "XLSX, CSV ya PDF file recipients ko email se milti hai; default XLSX hota hai.",
    ),
    "scheduled-reports.fieldRules.4.name": (
        "Status",
        "स्थिति",
        "स्थिती",
        "Status",
    ),
    "scheduled-reports.fieldRules.4.description": (
        "Toggle pauses or resumes delivery in place, keeping the schedule's configuration.",
        "Toggle delivery को वहीं पर pause या resume करता है, और schedule की configuration बनी रहती है।",
        "Toggle delivery तिथेच pause किंवा resume करते, आणि schedule ची configuration तशीच राहते.",
        "Toggle delivery ko wahin pause ya resume karta hai, aur schedule ki configuration wahi rehti hai.",
    ),
    "scheduled-reports.tip.title": (
        "Delete has no confirmation",
        "Delete की कोई पुष्टि नहीं होती",
        "Delete ची कोणतीही पुष्टी नाही",
        "Delete ka koi confirmation nahi hota",
    ),
    "scheduled-reports.tip.body": (
        "Clicking the trash icon deletes the schedule immediately — no confirmation dialog. If you might need it again, use the Active/Paused toggle instead of deleting.",
        "trash icon पर क्लिक करते ही schedule तुरंत delete हो जाता है — कोई confirmation dialog नहीं आता। अगर दोबारा ज़रूरत पड़ सकती है, तो delete करने के बजाय Active/Paused toggle का इस्तेमाल करें।",
        "trash icon वर क्लिक करताच schedule लगेच delete होते — कोणताही confirmation dialog येत नाही. पुन्हा गरज लागू शकते असे वाटल्यास, delete करण्याऐवजी Active/Paused toggle वापरा.",
        "Trash icon par click karte hi schedule turant delete ho jaata hai — koi confirmation dialog nahi aata. Agar dobara zaroorat pad sakti hai, to delete karne ke bajaye Active/Paused toggle 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 SCHEDULED_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(SCHEDULED_REPORTS)} scheduled-reports keys.")


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