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

Usage: docker compose exec api python seed_translations_pageinfo_ai_intelligence.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)
AI_INTELLIGENCE = {
    "ai-intelligence.title": (
        "AAMS AI Intelligence",
        "AAMS AI इंटेलिजेंस",
        "AAMS AI इंटेलिजन्स",
        "AAMS AI Intelligence",
    ),
    "ai-intelligence.subtitle": (
        "Predictive maintenance, anomaly detection & asset lifecycle intelligence — roadmap status",
        "प्रेडिक्टिव मेंटेनेंस, एनोमली डिटेक्शन और asset lifecycle इंटेलिजेंस — रोडमैप स्थिति",
        "प्रेडिक्टिव्ह मेंटेनन्स, एनोमली डिटेक्शन आणि asset lifecycle इंटेलिजन्स — रोडमॅप स्थिती",
        "Predictive maintenance, anomaly detection, aur asset lifecycle intelligence — roadmap status",
    ),
    "ai-intelligence.body.0": (
        "This page reports the real, live status of AAMS's AI/ML layer — it is not a working assistant yet. The backend's ai.py router is an explicit Phase 1 stub: predictions, remaining-useful-life and anomaly-detection endpoints all return a documented 501 by design until enough operational data (work orders, verification scans, depreciation history) accumulates to train models on.",
        "यह पेज AAMS की AI/ML लेयर की वास्तविक, live स्थिति दिखाता है — यह अभी कोई काम करने वाला assistant नहीं है। बैकएंड का ai.py router जानबूझकर एक Phase 1 stub है: predictions, remaining-useful-life और anomaly-detection endpoints सभी डिज़ाइन के अनुसार एक डॉक्यूमेंटेड 501 लौटाते हैं, जब तक models को train करने के लिए पर्याप्त operational data (work orders, verification scans, depreciation history) जमा नहीं हो जाता।",
        "हे पेज AAMS च्या AI/ML लेयरची खरी, live स्थिती दाखवते — हे अजून काम करणारा assistant नाही. बॅकएंडचा ai.py router मुद्दाम एक Phase 1 stub आहे: predictions, remaining-useful-life आणि anomaly-detection endpoints सर्व डिझाइननुसार एक डॉक्युमेंटेड 501 परत करतात, जोपर्यंत models train करण्यासाठी पुरेसा operational data (work orders, verification scans, depreciation history) जमा होत नाही.",
        "Ye page AAMS ke AI/ML layer ka real, live status batata hai — ye abhi koi kaam karne wala assistant nahi hai. Backend ka ai.py router jaan-boojh kar ek Phase 1 stub hai: predictions, remaining-useful-life, aur anomaly-detection endpoints sab design ke hisaab se ek documented 501 return karte hain, jab tak models train karne ke liye enough operational data (work orders, verification scans, depreciation history) accumulate nahi ho jaata.",
    ),
    "ai-intelligence.body.1": (
        "Use it to check what's planned, what data readiness looks like, and to prove for yourself that a given endpoint is a genuine stub rather than a silent failure.",
        "इसका उपयोग यह जांचने के लिए करें कि क्या योजना बनाई गई है, data readiness कैसी है, और यह स्वयं प्रमाणित करने के लिए कि दिया गया endpoint एक silent failure नहीं बल्कि वास्तविक stub है।",
        "याचा वापर हे तपासण्यासाठी करा की काय नियोजित आहे, data readiness कशी आहे, आणि स्वतः हे सिद्ध करण्यासाठी की दिलेला endpoint silent failure नसून खरा stub आहे.",
        "Isse check karein ki kya planned hai, data readiness kaisi hai, aur khud prove karein ki diya gaya endpoint ek genuine stub hai, na ki silent failure.",
    ),
    "ai-intelligence.stepsHeading": (
        "How this page works",
        "यह पेज कैसे काम करता है",
        "हे पेज कसे कार्य करते",
        "Ye page kaise kaam karta hai",
    ),
    "ai-intelligence.steps.0.label": (
        "Check Status",
        "स्थिति जांचें",
        "स्थिती तपासा",
        "Status check karein",
    ),
    "ai-intelligence.steps.0.caption": (
        "Phase and data-readiness banner loads from GET /ai/status.",
        "Phase और data-readiness बैनर GET /ai/status से लोड होता है।",
        "Phase आणि data-readiness बॅनर GET /ai/status वरून लोड होतो.",
        "Phase aur data-readiness banner GET /ai/status se load hota hai.",
    ),
    "ai-intelligence.steps.1.label": (
        "Planned Endpoints",
        "योजनाबद्ध Endpoints",
        "नियोजित Endpoints",
        "Planned Endpoints",
    ),
    "ai-intelligence.steps.1.caption": (
        "See which AI/ML APIs are mapped for future phases.",
        "देखें कि कौन-से AI/ML APIs भविष्य के phases के लिए मैप किए गए हैं।",
        "कोणते AI/ML APIs भविष्यातील phases साठी मॅप केले आहेत ते पहा.",
        "Dekhein kaunse AI/ML APIs future phases ke liye map kiye gaye hain.",
    ),
    "ai-intelligence.steps.2.label": (
        "Enter Asset ID",
        "Asset ID दर्ज करें",
        "Asset ID प्रविष्ट करा",
        "Asset ID enter karein",
    ),
    "ai-intelligence.steps.2.caption": (
        "Type an existing asset's ID to test against a real endpoint.",
        "किसी मौजूदा asset की ID टाइप करें ताकि इसे किसी वास्तविक endpoint के विरुद्ध टेस्ट किया जा सके।",
        "एखाद्या existing asset ची ID टाइप करा जेणेकरून खऱ्या endpoint विरुद्ध टेस्ट करता येईल.",
        "Kisi existing asset ki ID type karein taaki ek real endpoint ke against test kiya ja sake.",
    ),
    "ai-intelligence.steps.3.label": (
        "Try a Stub",
        "एक Stub आज़माएँ",
        "एक Stub वापरून पहा",
        "Ek Stub try karein",
    ),
    "ai-intelligence.steps.3.caption": (
        "Call Predictions / RUL / Anomaly and see the live 501 response.",
        "Predictions / RUL / Anomaly को कॉल करें और live 501 response देखें।",
        "Predictions / RUL / Anomaly कॉल करा आणि live 501 response पहा.",
        "Predictions / RUL / Anomaly ko call karein aur live 501 response dekhein.",
    ),
    "ai-intelligence.fieldRules.0.name": (
        "Asset ID",
        "Asset ID",
        "Asset ID",
        "Asset ID",
    ),
    "ai-intelligence.fieldRules.0.description": (
        "Must be filled before Predictions/RUL/Anomaly buttons enable — no format validation, it's passed straight to the endpoint.",
        "Predictions/RUL/Anomaly बटन सक्रिय होने से पहले इसे भरना ज़रूरी है — कोई format validation नहीं है, यह सीधे endpoint को पास कर दिया जाता है।",
        "Predictions/RUL/Anomaly बटणे सक्रिय होण्यापूर्वी हे भरणे आवश्यक आहे — कोणतेही format validation नाही, ते थेट endpoint ला पास केले जाते.",
        "Predictions/RUL/Anomaly buttons enable hone se pehle ye fill karna zaroori hai — koi format validation nahi hai, ye seedha endpoint ko pass ho jaata hai.",
    ),
    "ai-intelligence.fieldRules.1.name": (
        "Endpoint",
        "Endpoint",
        "Endpoint",
        "Endpoint",
    ),
    "ai-intelligence.fieldRules.1.description": (
        "The planned AI/ML API path shown in the Planned Endpoints table.",
        "Planned Endpoints टेबल में दिखाया गया योजनाबद्ध AI/ML API path।",
        "Planned Endpoints टेबलमध्ये दाखवलेला नियोजित AI/ML API path.",
        "Planned Endpoints table mein dikhaya gaya planned AI/ML API path.",
    ),
    "ai-intelligence.fieldRules.2.name": (
        "Data readiness",
        "Data Readiness",
        "Data Readiness",
        "Data readiness",
    ),
    "ai-intelligence.fieldRules.2.description": (
        "Backend's own assessment of whether enough historical data exists to eventually train on.",
        "यह बैकएंड का अपना आकलन है कि क्या भविष्य में models train करने के लिए पर्याप्त historical data मौजूद है।",
        "हे बॅकएंडचे स्वतःचे मूल्यांकन आहे की भविष्यात models train करण्यासाठी पुरेसा historical data अस्तित्वात आहे का.",
        "Ye backend ka apna assessment hai ki aage jaake models train karne ke liye enough historical data exist karta hai ya nahi.",
    ),
    "ai-intelligence.tip.title": (
        "A 501 here is expected, not a bug",
        "यहाँ 501 अपेक्षित है, कोई bug नहीं",
        "इथे 501 अपेक्षित आहे, bug नाही",
        "Yahan 501 expected hai, bug nahi",
    ),
    "ai-intelligence.tip.body": (
        "If Try a Stub Endpoint returns 501, that's the documented Phase 1 behavior working correctly — it is not a network or asset-ID error. Don't file it as a defect; check the message text for the reason (e.g. insufficient data).",
        "अगर Try a Stub Endpoint 501 लौटाता है, तो यह डॉक्यूमेंटेड Phase 1 व्यवहार सही ढंग से काम करने का संकेत है — यह कोई network या asset-ID error नहीं है। इसे defect के रूप में दर्ज न करें; कारण जानने के लिए message text जांचें (जैसे insufficient data)।",
        "जर Try a Stub Endpoint 501 परत करत असेल, तर हे डॉक्युमेंटेड Phase 1 वर्तन योग्यरित्या कार्य करत असल्याचे लक्षण आहे — ही network किंवा asset-ID error नाही. हे defect म्हणून नोंदवू नका; कारणासाठी message text तपासा (उदा. insufficient data).",
        "Agar Try a Stub Endpoint 501 return karta hai, to ye documented Phase 1 behavior sahi tarah kaam kar raha hai — ye koi network ya asset-ID error nahi hai. Isse defect ke roop mein file mat karein; reason ke liye message text check karein (jaise insufficient data).",
    ),
}


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 AI_INTELLIGENCE.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(AI_INTELLIGENCE)} ai-intelligence keys.")


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