"""One-off seed: populate translation_keys/translation_values for the
"common" namespace (currently just the 7 login-screen strings) so the
pre-login language switcher on AuthScreens.tsx has real content to show,
not just English everywhere.

Usage: docker compose exec api python seed_translations_common.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 = "common"

SOURCE_TEXT = {
    "auth.login.welcomeBack": "Welcome Back",
    "auth.login.subtitle": "Sign in to access your secure enterprise operations dashboard.",
    "auth.login.emailLabel": "Email Address",
    "auth.login.passwordLabel": "Password",
    "auth.login.mfaPlaceholder": "6-digit code, or a recovery code",
    "auth.login.signIn": "Sign In",
    "auth.login.signInWithSso": "Sign in with Enterprise SSO Identity",
}

VALUES_BY_LANG = {
    "hi": {
        "auth.login.welcomeBack": "वापसी पर स्वागत है",
        "auth.login.subtitle": "अपने सुरक्षित एंटरप्राइज़ ऑपरेशंस डैशबोर्ड तक पहुँचने के लिए साइन इन करें।",
        "auth.login.emailLabel": "ईमेल पता",
        "auth.login.passwordLabel": "पासवर्ड",
        "auth.login.mfaPlaceholder": "6-अंकों का कोड, या एक रिकवरी कोड",
        "auth.login.signIn": "साइन इन करें",
        "auth.login.signInWithSso": "एंटरप्राइज़ SSO पहचान से साइन इन करें",
    },
    "mr": {
        "auth.login.welcomeBack": "पुन्हा स्वागत आहे",
        "auth.login.subtitle": "तुमच्या सुरक्षित एंटरप्राइझ ऑपरेशन्स डॅशबोर्डमध्ये प्रवेश करण्यासाठी साइन इन करा.",
        "auth.login.emailLabel": "ईमेल पत्ता",
        "auth.login.passwordLabel": "पासवर्ड",
        "auth.login.mfaPlaceholder": "6-अंकी कोड, किंवा रिकव्हरी कोड",
        "auth.login.signIn": "साइन इन करा",
        "auth.login.signInWithSso": "एंटरप्राइझ SSO ओळखीने साइन इन करा",
    },
    "hinglish": {
        "auth.login.welcomeBack": "Welcome Back",
        "auth.login.subtitle": "Apne secure enterprise operations dashboard tak access karne ke liye sign in karein.",
        "auth.login.emailLabel": "Email Address",
        "auth.login.passwordLabel": "Password",
        "auth.login.mfaPlaceholder": "6-digit code, ya ek recovery code",
        "auth.login.signIn": "Sign In Karein",
        "auth.login.signInWithSso": "Enterprise SSO Identity se Sign In Karein",
    },
}


async def seed_translations_common(session: AsyncSession) -> None:
    now = datetime.now(timezone.utc)
    key_ids = {}
    for key, source_text in SOURCE_TEXT.items():
        existing = (await session.execute(
            text("SELECT id FROM translation_keys WHERE namespace = :ns AND key = :key"),
            {"ns": NAMESPACE, "key": key},
        )).scalar_one_or_none()
        if existing:
            key_ids[key] = existing
            await session.execute(
                text("UPDATE translation_keys SET source_text = :src WHERE id = :id"),
                {"src": source_text, "id": existing},
            )
        else:
            new_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": new_id, "ns": NAMESPACE, "key": key, "src": source_text, "now": now},
            )
            key_ids[key] = new_id

    for lang_code, values in VALUES_BY_LANG.items():
        for key, value in values.items():
            key_id = key_ids[key]
            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},
                )

    await session.commit()


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:
                await seed_translations_common(session)
                print(f"  seeded common translations: {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.")


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