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

Usage: docker compose exec api python seed_translations_pageinfo_warranty_tracking.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)
WARRANTY_TRACKING = {
    "warranty-tracking.title": (
        "Warranty & Insurance",
        "वारंटी और बीमा",
        "वॉरंटी आणि विमा",
        "Warranty & Insurance",
    ),
    "warranty-tracking.subtitle": (
        "Insurance policies, claims, coverage reports, and tenant-wide warranty tools",
        "बीमा पॉलिसियाँ, दावे, कवरेज रिपोर्ट, और टेनेंट-व्यापी वारंटी टूल्स",
        "विमा पॉलिसी, दावे, कव्हरेज अहवाल, आणि टेनंट-व्यापी वॉरंटी साधने",
        "Insurance policies, claims, coverage reports, aur tenant-wide warranty tools",
    ),
    "warranty-tracking.body.0": (
        "Register and renew insurance policies (fire, machinery, comprehensive, marine), file claims against them, and track coverage gaps and loss ratios — all tenant-wide.",
        "बीमा पॉलिसियाँ (fire, machinery, comprehensive, marine) रजिस्टर और रिन्यू करें, उनके विरुद्ध दावे दर्ज करें, और कवरेज गैप्स तथा loss ratios को ट्रैक करें — यह सब टेनेंट-व्यापी स्तर पर।",
        "विमा पॉलिसी (fire, machinery, comprehensive, marine) नोंदवा आणि नूतनीकरण करा, त्यांच्याविरुद्ध दावे दाखल करा, आणि कव्हरेज गॅप्स व loss ratios ट्रॅक करा — हे सर्व टेनंट-व्यापी पातळीवर.",
        "Insurance policies (fire, machinery, comprehensive, marine) register aur renew karein, unke against claims file karein, aur coverage gaps aur loss ratios track karein — ye sab tenant-wide level par.",
    ),
    "warranty-tracking.body.1": (
        "Per-asset warranty registration, claims, and overrides live on each asset's Asset Details → Warranty tab. This page's Warranty Tools tab only covers tenant-wide analytics (pending claims value, cost avoidance) and moving a warranty between assets.",
        "प्रति-asset वारंटी रजिस्ट्रेशन, दावे, और overrides हर asset के Asset Details → Warranty टैब पर मौजूद होते हैं। इस पेज का Warranty Tools टैब केवल टेनेंट-व्यापी analytics (pending claims value, cost avoidance) और दो assets के बीच वारंटी को स्थानांतरित करने को कवर करता है।",
        "प्रति-asset वॉरंटी नोंदणी, दावे, आणि overrides प्रत्येक asset च्या Asset Details → Warranty टॅबवर असतात. या पेजचा Warranty Tools टॅब फक्त टेनंट-व्यापी analytics (pending claims value, cost avoidance) आणि दोन assets मधील वॉरंटी स्थानांतरित करणे कव्हर करतो.",
        "Per-asset warranty registration, claims, aur overrides har asset ke Asset Details → Warranty tab par milte hain. Is page ka Warranty Tools tab sirf tenant-wide analytics (pending claims value, cost avoidance) aur ek asset se dusre asset mein warranty move karne ko cover karta hai.",
    ),
    "warranty-tracking.stepsHeading": (
        "Claim lifecycle",
        "दावा जीवनचक्र",
        "दावा जीवनचक्र",
        "Claim lifecycle",
    ),
    "warranty-tracking.steps.0.label": ("Filed", "दर्ज किया गया", "दाखल केले", "Filed"),
    "warranty-tracking.steps.0.caption": (
        "Claim raised against a policy",
        "पॉलिसी के विरुद्ध दावा उठाया गया",
        "पॉलिसीविरुद्ध दावा नोंदवला",
        "Policy ke against claim raise kiya gaya",
    ),
    "warranty-tracking.steps.1.label": ("Under Review", "समीक्षाधीन", "पुनरावलोकनाधीन", "Under Review"),
    "warranty-tracking.steps.1.caption": (
        "Moved forward for assessment",
        "आकलन के लिए आगे बढ़ाया गया",
        "मूल्यांकनासाठी पुढे पाठवले",
        "Assessment ke liye aage badhaya gaya",
    ),
    "warranty-tracking.steps.2.label": ("Settled", "निपटाया गया", "निकाली काढले", "Settled"),
    "warranty-tracking.steps.2.caption": (
        "Amount + settlement type recorded",
        "राशि + settlement प्रकार दर्ज किया गया",
        "रक्कम + settlement प्रकार नोंदवला",
        "Amount + settlement type record kiya gaya",
    ),
    "warranty-tracking.steps.3.label": ("Rejected", "अस्वीकृत", "नाकारले", "Rejected"),
    "warranty-tracking.steps.3.caption": (
        "Closed with no payout",
        "बिना भुगतान के बंद किया गया",
        "पेआउटशिवाय बंद केले",
        "Bina payout ke close kar diya gaya",
    ),
    "warranty-tracking.fieldRules.0.name": ("Policy Number", "पॉलिसी नंबर", "पॉलिसी नंबर", "Policy Number"),
    "warranty-tracking.fieldRules.0.description": (
        "Unique policy identifier — locked and cannot be edited once the policy is created.",
        "अद्वितीय पॉलिसी पहचानकर्ता — पॉलिसी बनने के बाद यह लॉक हो जाता है और इसे संपादित नहीं किया जा सकता।",
        "अद्वितीय पॉलिसी ओळखकर्ता — पॉलिसी तयार झाल्यानंतर हे लॉक होते आणि संपादित करता येत नाही.",
        "Unique policy identifier — policy create hone ke baad ye lock ho jaata hai aur edit nahi kiya ja sakta.",
    ),
    "warranty-tracking.fieldRules.1.name": ("Policy Type", "पॉलिसी प्रकार", "पॉलिसी प्रकार", "Policy Type"),
    "warranty-tracking.fieldRules.1.description": (
        "Fire, Machinery, Comprehensive, or Marine — drives coverage and reporting classification.",
        "Fire, Machinery, Comprehensive, या Marine — यह coverage और reporting classification को निर्धारित करता है।",
        "Fire, Machinery, Comprehensive, किंवा Marine — हे कव्हरेज आणि रिपोर्टिंग classification ठरवते.",
        "Fire, Machinery, Comprehensive, ya Marine — ye coverage aur reporting classification decide karta hai.",
    ),
    "warranty-tracking.fieldRules.2.name": ("Coverage Type", "कवरेज प्रकार", "कव्हरेज प्रकार", "Coverage Type"),
    "warranty-tracking.fieldRules.2.description": (
        "Blanket covers all assets under the sum insured; Asset Specific unlocks the Link Assets action to tie the policy to individual asset IDs.",
        "Blanket, sum insured के अंतर्गत सभी assets को कवर करता है; Asset Specific, पॉलिसी को व्यक्तिगत asset IDs से जोड़ने के लिए Link Assets एक्शन को अनलॉक करता है।",
        "Blanket, sum insured अंतर्गत सर्व assets कव्हर करते; Asset Specific, पॉलिसीला वैयक्तिक asset IDs शी जोडण्यासाठी Link Assets action अनलॉक करते.",
        "Blanket sum insured ke under sabhi assets cover karta hai; Asset Specific, policy ko individual asset IDs se link karne ke liye Link Assets action unlock karta hai.",
    ),
    "warranty-tracking.fieldRules.3.name": (
        "Sum Insured / Premium",
        "Sum Insured / Premium",
        "Sum Insured / Premium",
        "Sum Insured / Premium",
    ),
    "warranty-tracking.fieldRules.3.description": (
        "Both must be greater than zero — validated on submit.",
        "दोनों शून्य से अधिक होने चाहिए — submit करते समय validate किया जाता है।",
        "दोन्ही शून्यापेक्षा जास्त असणे आवश्यक आहे — submit करताना validate केले जाते.",
        "Dono zero se zyada hone chahiye — submit karte time validate kiya jaata hai.",
    ),
    "warranty-tracking.fieldRules.4.name": ("End Date", "अंतिम तिथि", "शेवटची तारीख", "End Date"),
    "warranty-tracking.fieldRules.4.description": (
        "Policy expiry — switch the view to \"Expiring (90 days)\" to see policies nearing this date.",
        "पॉलिसी की expiry — इस तिथि के निकट पॉलिसियाँ देखने के लिए view को \"Expiring (90 days)\" पर स्विच करें।",
        "पॉलिसीची expiry — या तारखेजवळील पॉलिसी पाहण्यासाठी view \"Expiring (90 days)\" वर स्विच करा.",
        "Policy ki expiry — is date ke paas wali policies dekhne ke liye view ko \"Expiring (90 days)\" par switch karein.",
    ),
    "warranty-tracking.tip.title": (
        "Link Assets needs Asset Specific coverage",
        "Link Assets के लिए Asset Specific कवरेज आवश्यक है",
        "Link Assets साठी Asset Specific कव्हरेज आवश्यक आहे",
        "Link Assets ke liye Asset Specific coverage chahiye",
    ),
    "warranty-tracking.tip.body": (
        "The Link Assets action only appears for policies set to \"Asset Specific\" coverage. If you registered a policy as \"Blanket\" and need to attach it to particular assets, edit the policy and change Coverage Type first — otherwise the link icon simply won't show up.",
        "Link Assets एक्शन केवल उन पॉलिसियों के लिए दिखाई देता है जिनका coverage \"Asset Specific\" सेट है। यदि आपने किसी पॉलिसी को \"Blanket\" के रूप में रजिस्टर किया है और उसे विशिष्ट assets से जोड़ना है, तो पहले पॉलिसी को edit करके Coverage Type बदलें — अन्यथा link आइकन बिल्कुल दिखाई नहीं देगा।",
        "Link Assets action फक्त \"Asset Specific\" कव्हरेज सेट असलेल्या पॉलिसींसाठीच दिसते. जर तुम्ही एखादी पॉलिसी \"Blanket\" म्हणून नोंदवली असेल आणि ती विशिष्ट assets शी जोडायची असेल, तर आधी पॉलिसी edit करून Coverage Type बदला — नाहीतर link आयकॉन अजिबात दिसणार नाही.",
        "Link Assets action sirf un policies ke liye dikhta hai jinka coverage \"Asset Specific\" set hai. Agar aapne koi policy \"Blanket\" ke roop mein register ki hai aur use specific assets se attach karna hai, to pehle policy edit karke Coverage Type badlein — warna link icon bilkul nahi dikhega.",
    ),
}


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 WARRANTY_TRACKING.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(WARRANTY_TRACKING)} warranty-tracking keys.")


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