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

Usage: docker compose exec api python seed_translations_pageinfo_geo_workspace.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)
GEO_WORKSPACE = {
    "geo-workspace.title": (
        "Geo Workspace",
        "जियो वर्कस्पेस",
        "जिओ वर्कस्पेस",
        "Geo Workspace",
    ),
    "geo-workspace.subtitle": (
        "GPS reference points, geofences, and spatial asset queries",
        "GPS संदर्भ बिंदु, geofences, और asset से जुड़ी spatial queries",
        "GPS संदर्भ बिंदू, geofences, आणि asset शी संबंधित spatial queries",
        "GPS reference points, geofences, aur asset ki spatial queries",
    ),
    "geo-workspace.body.0": (
        "GPS reference points, geofences, and spatial asset queries.",
        "GPS संदर्भ बिंदु, geofences, और asset से जुड़ी spatial queries।",
        "GPS संदर्भ बिंदू, geofences, आणि asset शी संबंधित spatial queries.",
        "GPS reference points, geofences, aur asset ki spatial queries.",
    ),
    "geo-workspace.body.1": (
        "A single asset's own position lives on its Location tab — this workspace is for the shared geo infrastructure those checks run against.",
        "किसी individual asset की अपनी position उसके Location टैब पर होती है — यह workspace उस साझा geo infrastructure के लिए है जिसके विरुद्ध वे checks चलते हैं।",
        "एखाद्या individual asset ची स्वतःची position त्याच्या Location टॅबवर असते — हे workspace त्या shared geo infrastructure साठी आहे ज्याविरुद्ध ते checks चालतात.",
        "Kisi single asset ki apni position uske Location tab par hoti hai — ye workspace us shared geo infrastructure ke liye hai jiske against wo checks chalte hain.",
    ),
    "geo-workspace.stepsHeading": (
        "Five workspace tools",
        "पाँच workspace टूल्स",
        "पाच workspace टूल्स",
        "Paanch workspace tools",
    ),
    "geo-workspace.steps.0.label": ("Geo Locations", "जियो लोकेशन्स", "जिओ लोकेशन्स", "Geo Locations"),
    "geo-workspace.steps.0.caption": (
        "Register a GPS point tied to a master location",
        "किसी master location से जुड़ा GPS पॉइंट रजिस्टर करें",
        "एखाद्या master location शी जोडलेला GPS पॉइंट रजिस्टर करा",
        "Kisi master location se linked GPS point register karein",
    ),
    "geo-workspace.steps.1.label": ("Geofences", "जियोफेंस", "जिओफेन्स", "Geofences"),
    "geo-workspace.steps.1.caption": (
        "Draw a radius around a location; enable breach alerts",
        "किसी location के चारों ओर radius बनाएँ; breach alerts चालू करें",
        "एखाद्या location भोवती radius काढा; breach alerts सुरू करा",
        "Kisi location ke around radius draw karein; breach alerts enable karein",
    ),
    "geo-workspace.steps.2.label": ("Geofence Check", "जियोफेंस चेक", "जिओफेन्स चेक", "Geofence Check"),
    "geo-workspace.steps.2.caption": (
        "Test if one coordinate falls inside an active fence",
        "जाँचें कि कोई coordinate किसी active fence के अंदर आता है या नहीं",
        "एखादा coordinate active fence च्या आत येतो का हे तपासा",
        "Check karein ki koi coordinate active fence ke andar aata hai ya nahi",
    ),
    "geo-workspace.steps.3.label": ("Map Search", "मैप सर्च", "मॅप सर्च", "Map Search"),
    "geo-workspace.steps.3.caption": (
        "Find assets near a point or inside a bounding box",
        "किसी point के पास या bounding box के अंदर assets खोजें",
        "एखाद्या point जवळ किंवा bounding box च्या आत assets शोधा",
        "Kisi point ke paas ya bounding box ke andar assets dhundhein",
    ),
    "geo-workspace.steps.4.label": ("Unverified Report", "असत्यापित रिपोर्ट", "अपुष्ट रिपोर्ट", "Unverified Report"),
    "geo-workspace.steps.4.caption": (
        "List assets whose GPS location hasn't been checked recently",
        "उन assets की सूची जिनकी GPS location हाल में चेक नहीं हुई है",
        "ज्या assets ची GPS location अलीकडे चेक झालेली नाही त्यांची यादी",
        "Un assets ki list jinki GPS location recently check nahi hui hai",
    ),
    "geo-workspace.fieldRules.0.name": (
        "Latitude / Longitude",
        "लैटिट्यूड / लॉन्गिट्यूड",
        "लॅटिट्यूड / लाँगिट्यूड",
        "Latitude / Longitude",
    ),
    "geo-workspace.fieldRules.0.description": (
        "Decimal GPS coordinates; Create is blocked if either isn't a valid number.",
        "Decimal GPS coordinates; अगर इनमें से कोई भी valid number नहीं है तो Create ब्लॉक हो जाता है।",
        "Decimal GPS coordinates; यापैकी कोणतीही valid number नसेल तर Create ब्लॉक होते.",
        "Decimal GPS coordinates; agar in mein se koi bhi valid number nahi hai to Create block ho jaata hai.",
    ),
    "geo-workspace.fieldRules.1.name": ("Location", "लोकेशन", "लोकेशन", "Location"),
    "geo-workspace.fieldRules.1.description": (
        "Links the point to a master Location. Optional on a Geo Location, required on a Geofence.",
        "पॉइंट को किसी master Location से लिंक करता है। Geo Location पर वैकल्पिक (optional), Geofence पर आवश्यक (required)।",
        "पॉइंटला master Location शी लिंक करते. Geo Location वर optional, Geofence वर required.",
        "Point ko ek master Location se link karta hai. Geo Location par optional, Geofence par required.",
    ),
    "geo-workspace.fieldRules.2.name": ("Radius (m)", "रेडियस (मी.)", "रेडियस (मी.)", "Radius (m)"),
    "geo-workspace.fieldRules.2.description": (
        "Geofence radius around the center point, in meters; defaults to 100.",
        "Center point के चारों ओर Geofence radius, मीटर में; डिफ़ॉल्ट रूप से 100।",
        "Center point भोवती Geofence radius, मीटरमध्ये; डीफॉल्टने 100.",
        "Center point ke around Geofence radius, meters mein; default 100 hota hai.",
    ),
    "geo-workspace.fieldRules.3.name": ("Alert on Breach", "ब्रीच पर अलर्ट", "ब्रीचवर अलर्ट", "Alert on Breach"),
    "geo-workspace.fieldRules.3.description": (
        "Whether crossing the fence boundary raises a notification.",
        "क्या fence boundary पार करने पर notification आता है।",
        "fence boundary ओलांडल्यावर notification येते का.",
        "Fence boundary cross karne par notification aata hai ya nahi.",
    ),
    "geo-workspace.tip.title": (
        "Create/manage controls hidden?",
        "Create/manage controls दिख नहीं रहे?",
        "Create/manage controls दिसत नाहीत?",
        "Create/manage controls hidden hain?",
    ),
    "geo-workspace.tip.body": (
        "The New/Delete/Activate controls need the geo:create permission, not master:create — a user who can manage Location Masters may still not see them here.",
        "New/Delete/Activate controls के लिए geo:create permission चाहिए, master:create नहीं — जो user Location Masters manage कर सकता है, हो सकता है उसे यहाँ ये फिर भी न दिखें।",
        "New/Delete/Activate controls साठी geo:create permission लागते, master:create नाही — जो user Location Masters manage करू शकतो, त्याला ते इथे तरीही दिसणार नाहीत.",
        "New/Delete/Activate controls ke liye geo:create permission chahiye, master:create nahi — jo user Location Masters manage kar sakta hai, usko ye yahan phir bhi nahi dikh sakte.",
    ),
}


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 GEO_WORKSPACE.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(GEO_WORKSPACE)} geo-workspace keys.")


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