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

Usage: docker compose exec api python seed_translations_pageinfo_compliance_center.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)
COMPLIANCE_CENTER = {
    "compliance-center.title": (
        "Compliance Center",
        "अनुपालन केंद्र",
        "अनुपालन केंद्र",
        "Compliance Center",
    ),
    "compliance-center.subtitle": (
        "Expiring documents, statutory calendar, and ISO 55001 readiness — three lenses on organisational compliance.",
        "समाप्त होने वाले दस्तावेज़, वैधानिक कैलेंडर, और ISO 55001 तैयारी — संगठनात्मक अनुपालन को देखने के तीन नज़रिए।",
        "कालबाह्य होणारी कागदपत्रे, वैधानिक कॅलेंडर, आणि ISO 55001 तयारी — संस्थात्मक अनुपालन पाहण्याचे तीन दृष्टिकोन.",
        "Expiring documents, statutory calendar, aur ISO 55001 readiness — organisational compliance ko dekhne ke teen lenses.",
    ),
    "compliance-center.body.0": (
        "Expiring Documents flags asset documents (warranties, licences, certificates, insurance) nearing expiry within a selectable window, and can trigger a background job that dispatches alerts to responsible users.",
        "Expiring Documents उन asset दस्तावेज़ों (warranties, licences, certificates, insurance) को फ़्लैग करता है जो चुने गए विंडो के भीतर समाप्ति के करीब हैं, और यह एक background job को ट्रिगर कर सकता है जो ज़िम्मेदार उपयोगकर्ताओं को alerts भेजता है।",
        "Expiring Documents त्या asset दस्तऐवजांना (warranties, licences, certificates, insurance) फ्लॅग करते जे निवडलेल्या विंडोमध्ये मुदत संपण्याच्या जवळ आहेत, आणि हे एक background job ट्रिगर करू शकते जे जबाबदार वापरकर्त्यांना alerts पाठवते.",
        "Expiring Documents un asset documents (warranties, licences, certificates, insurance) ko flag karta hai jo selected window ke andar expiry ke kareeb hain, aur ye ek background job trigger kar sakta hai jo responsible users ko alerts bhejta hai.",
    ),
    "compliance-center.body.1": (
        "Compliance Calendar aggregates the next 90 days of obligations — depreciation runs, ITC claims, document/warranty/insurance/contract expiries, and physical verification — as a single list you can mark complete.",
        "Compliance Calendar अगले 90 दिनों के दायित्वों — depreciation runs, ITC claims, document/warranty/insurance/contract की समाप्तियाँ, और physical verification — को एक ही सूची में एकत्र करता है, जिसे आप complete के रूप में चिह्नित कर सकते हैं।",
        "Compliance Calendar पुढील 90 दिवसांच्या जबाबदाऱ्या — depreciation runs, ITC claims, document/warranty/insurance/contract च्या मुदती, आणि physical verification — एका यादीत एकत्र करते, जी तुम्ही complete म्हणून चिन्हांकित करू शकता.",
        "Compliance Calendar agle 90 dino ke obligations — depreciation runs, ITC claims, document/warranty/insurance/contract expiries, aur physical verification — ko ek hi list mein aggregate karta hai, jise aap complete mark kar sakte hain.",
    ),
    "compliance-center.body.2": (
        "ISO 55001 Assessment scores organisational readiness live across four dimensions: asset register completeness, custody coverage, depreciation currency, and document coverage.",
        "ISO 55001 Assessment चार dimensions में संगठनात्मक तैयारी को लाइव स्कोर करता है: asset register की पूर्णता, custody coverage, depreciation currency, और document coverage।",
        "ISO 55001 Assessment चार dimensions मध्ये संस्थात्मक तयारीचे लाइव्ह स्कोअरिंग करते: asset register ची पूर्णता, custody coverage, depreciation currency, आणि document coverage.",
        "ISO 55001 Assessment char dimensions mein organisational readiness ko live score karta hai: asset register ki completeness, custody coverage, depreciation currency, aur document coverage.",
    ),
    "compliance-center.stepsHeading": (
        "Compliance event lifecycle",
        "अनुपालन इवेंट जीवनचक्र",
        "अनुपालन इव्हेंट जीवनचक्र",
        "Compliance event lifecycle",
    ),
    "compliance-center.steps.0.label": ("Generated", "जनरेट किया गया", "जनरेट केले", "Generated"),
    "compliance-center.steps.0.caption": (
        "Refresh Calendar builds events from asset/document/depreciation data",
        "Refresh Calendar, asset/document/depreciation डेटा से events बनाता है",
        "Refresh Calendar, asset/document/depreciation डेटावरून events तयार करते",
        "Refresh Calendar asset/document/depreciation data se events banata hai",
    ),
    "compliance-center.steps.1.label": ("Upcoming", "आगामी", "आगामी", "Upcoming"),
    "compliance-center.steps.1.caption": (
        "Pending, more than 14 days from its due date",
        "लंबित, अपनी नियत तारीख से 14 दिन से अधिक दूर",
        "प्रलंबित, त्याच्या देय तारखेपासून 14 दिवसांपेक्षा जास्त दूर",
        "Pending, apni due date se 14 din se zyada door",
    ),
    "compliance-center.steps.2.label": ("Urgent / Overdue", "अत्यावश्यक / अतिदेय", "तातडीचे / मुदत उलटलेले", "Urgent / Overdue"),
    "compliance-center.steps.2.caption": (
        "Amber inside 14 days, red once the due date passes",
        "14 दिनों के भीतर एम्बर (amber), नियत तारीख बीतने के बाद लाल (red)",
        "14 दिवसांच्या आत एम्बर (amber), देय तारीख उलटल्यावर लाल (red)",
        "14 din ke andar amber, due date nikalne ke baad red",
    ),
    "compliance-center.steps.3.label": ("Completed", "पूर्ण", "पूर्ण", "Completed"),
    "compliance-center.steps.3.caption": (
        "Marked complete via the Mark Complete action",
        "Mark Complete एक्शन के ज़रिए पूर्ण के रूप में चिह्नित",
        "Mark Complete अ‍ॅक्शनद्वारे पूर्ण म्हणून चिन्हांकित",
        "Mark Complete action ke through complete mark kiya gaya",
    ),
    "compliance-center.fieldRules.0.name": ("Window", "विंडो (Window)", "विंडो (Window)", "Window"),
    "compliance-center.fieldRules.0.description": (
        "Sets how many days ahead to scan for expiring documents (7-180); independent of the Calendar tab, which is always fixed to the next 90 days.",
        "यह तय करता है कि expiring documents के लिए कितने दिन आगे तक स्कैन किया जाए (7-180); यह Calendar tab से स्वतंत्र है, जो हमेशा अगले 90 दिनों पर तय रहता है।",
        "हे ठरवते की expiring documents साठी किती दिवस पुढे स्कॅन करायचे (7-180); हे Calendar tab पासून स्वतंत्र आहे, जे नेहमी पुढील 90 दिवसांवर निश्चित असते.",
        "Ye decide karta hai ki expiring documents ke liye kitne din aage scan karna hai (7-180); ye Calendar tab se independent hai, jo hamesha agle 90 din par fixed rehta hai.",
    ),
    "compliance-center.fieldRules.1.name": ("Days Left", "शेष दिन (Days Left)", "उरलेले दिवस (Days Left)", "Days Left"),
    "compliance-center.fieldRules.1.description": (
        "Computed from the expiry date — shows red \"overdue\" once past due, amber inside 14 days.",
        "यह expiry date से गणना की जाती है — नियत तारीख बीतने पर लाल \"overdue\" दिखाता है, 14 दिनों के भीतर एम्बर।",
        "हे expiry date वरून मोजले जाते — देय तारीख उलटल्यावर लाल \"overdue\" दाखवते, 14 दिवसांच्या आत एम्बर.",
        "Ye expiry date se compute hota hai — due date nikalne ke baad red \"overdue\" dikhata hai, 14 din ke andar amber.",
    ),
    "compliance-center.fieldRules.2.name": ("Urgency", "अत्यावश्यकता (Urgency)", "तातडी (Urgency)", "Urgency"),
    "compliance-center.fieldRules.2.description": (
        "Auto-derived from the due date: overdue (red), urgent (amber), or upcoming (grey) — not user-editable.",
        "यह due date से स्वतः निकाला जाता है: overdue (लाल), urgent (एम्बर), या upcoming (ग्रे) — यूज़र द्वारा एडिट करने योग्य नहीं है।",
        "हे due date वरून आपोआप ठरवले जाते: overdue (लाल), urgent (एम्बर), किंवा upcoming (करडा) — वापरकर्त्याद्वारे संपादनयोग्य नाही.",
        "Ye due date se auto-derive hota hai: overdue (red), urgent (amber), ya upcoming (grey) — ye user-editable nahi hai.",
    ),
    "compliance-center.fieldRules.3.name": ("Status", "स्थिति (Status)", "स्थिती (Status)", "Status"),
    "compliance-center.fieldRules.3.description": (
        "pending / completed / overdue — the Mark Complete action only appears while an event isn't already completed.",
        "pending / completed / overdue — Mark Complete एक्शन तभी दिखता है जब कोई event पहले से पूर्ण न हो।",
        "pending / completed / overdue — Mark Complete अ‍ॅक्शन तेव्हाच दिसते जेव्हा एखादा event आधीच पूर्ण झालेला नसतो.",
        "pending / completed / overdue — Mark Complete action tabhi dikhta hai jab event pehle se complete na ho.",
    ),
    "compliance-center.fieldRules.4.name": ("Overall Readiness %", "कुल तैयारी % (Overall Readiness %)", "एकूण तयारी % (Overall Readiness %)", "Overall Readiness %"),
    "compliance-center.fieldRules.4.description": (
        "Live average of the four dimension scores below; recalculated each time you open the tab — there is no manual refresh control.",
        "नीचे दिए गए चार dimension scores का लाइव average; हर बार tab खोलने पर पुनर्गणना होती है — इसके लिए कोई मैनुअल रिफ्रेश कंट्रोल नहीं है।",
        "खाली दिलेल्या चार dimension scores चे लाइव्ह सरासरी; तुम्ही tab उघडता तेव्हा प्रत्येक वेळी पुन्हा गणना होते — यासाठी कोणतेही manual refresh control नाही.",
        "Neeche diye gaye char dimension scores ka live average; jab bhi aap tab open karte hain recalculate hota hai — iske liye koi manual refresh control nahi hai.",
    ),
    "compliance-center.tip.title": (
        "The Window filter and Calendar are independent",
        "Window फ़िल्टर और Calendar एक-दूसरे से स्वतंत्र हैं",
        "Window फिल्टर आणि Calendar एकमेकांपासून स्वतंत्र आहेत",
        "Window filter aur Calendar ek-dusre se independent hain",
    ),
    "compliance-center.tip.body": (
        "Widening the Expiring Documents window to 90 or 180 days does not change the Compliance Calendar — it always looks 90 days ahead regardless of what's selected there. To pick up newly generated events, use Refresh Calendar on the Calendar tab, not the Window dropdown.",
        "Expiring Documents की विंडो को 90 या 180 दिनों तक बढ़ाने से Compliance Calendar नहीं बदलता — यह हमेशा 90 दिन आगे तक देखता है, चाहे वहाँ कुछ भी चुना गया हो। नए बने events को शामिल करने के लिए, Window dropdown नहीं बल्कि Calendar tab पर Refresh Calendar का उपयोग करें।",
        "Expiring Documents ची विंडो 90 किंवा 180 दिवसांपर्यंत वाढवल्याने Compliance Calendar बदलत नाही — ते नेहमी 90 दिवस पुढे पाहते, तेथे काहीही निवडलेले असो. नव्याने तयार झालेले events मिळवण्यासाठी, Window dropdown नव्हे तर Calendar tab वरील Refresh Calendar वापरा.",
        "Expiring Documents ki window ko 90 ya 180 din tak badhane se Compliance Calendar change nahi hota — wo hamesha 90 din aage dekhta hai, chahe wahan kuch bhi selected ho. Newly generated events pick up karne ke liye, Window dropdown nahi balki Calendar tab par Refresh Calendar 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 COMPLIANCE_CENTER.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(COMPLIANCE_CENTER)} compliance-center keys.")


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