"""Seed feature-page UI strings into the "app" translation namespace so they
are managed on the Language Master page (fetched at runtime, no rebuild).

Each t() call site in ams-frontend passes its English text as defaultValue, so
English always renders; this seeds hi/mr/hinglish (and any future language).
Data lives in app_translations.json next to this file — append more feature
keys there as pages are internationalised, then re-run (idempotent upsert).

Usage: docker compose exec api python seed_translations_app.py
"""
import asyncio
import json
import os
import sys
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

# Optional CLI arg: path to a translations JSON (defaults to app_translations.json).
# The file's own "namespace" field decides which namespace is seeded, so the same
# seeder handles "app", "common", or any future namespace.
DATA_FILE = os.path.join(
    os.path.dirname(__file__),
    sys.argv[1] if len(sys.argv) > 1 else "app_translations.json",
)


def load_data():
    with open(DATA_FILE, encoding="utf-8") as f:
        d = json.load(f)
    return d["namespace"], d["source_text"], d["values_by_lang"]


async def seed(session: AsyncSession, namespace: str, source_text: dict, values_by_lang: dict) -> int:
    now = datetime.now(timezone.utc)
    key_ids = {}
    for key, src 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": src, "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": src, "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.get(key)
            if key_id is None:
                continue
            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()
    return len(source_text)


async def main() -> None:
    namespace, source_text, values_by_lang = load_data()
    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:
                n = await seed(session, namespace, source_text, values_by_lang)
                print(f"  seeded {n} app keys (hi/mr/hinglish): {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())
