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

Usage: docker compose exec api python seed_translations_pageinfo_journal_export.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)
JOURNAL_EXPORT = {
    "journal-export.title": (
        "Journal Export",
        "जर्नल एक्सपोर्ट",
        "जर्नल एक्सपोर्ट",
        "Journal Export",
    ),
    "journal-export.subtitle": (
        "Push a period's depreciation and financial entries out to your accounting system.",
        "किसी अवधि की depreciation और financial entries को अपने accounting system में भेजें।",
        "एखाद्या कालावधीच्या depreciation आणि financial entries तुमच्या accounting system मध्ये पाठवा.",
        "Kisi period ki depreciation aur financial entries ko apne accounting system mein push karein.",
    ),
    "journal-export.body.0": (
        "Generates journal entries — depreciation and other financial postings — for a chosen year/month and accounting book, then packages them in a format your external system can import (Tally, SAP, or PFMS for government books, or plain CSV).",
        "चुने गए year/month और accounting book के लिए journal entries — depreciation और अन्य financial postings — जनरेट करता है, फिर उन्हें ऐसे format में पैकेज करता है जिसे आपका external system import कर सके (Tally, SAP, या government books के लिए PFMS, या plain CSV)।",
        "निवडलेल्या year/month आणि accounting book साठी journal entries — depreciation आणि इतर financial postings — तयार करते, नंतर त्यांना अशा format मध्ये पॅकेज करते जे तुमची external system import करू शकेल (Tally, SAP, किंवा government books साठी PFMS, किंवा plain CSV).",
        "Chune gaye year/month aur accounting book ke liye journal entries — depreciation aur other financial postings — generate karta hai, phir unhe aise format mein package karta hai jise aapka external system import kar sake (Tally, SAP, ya government books ke liye PFMS, ya plain CSV).",
    ),
    "journal-export.body.1": (
        "Export runs as a background job. Submit it here, then use the Job ID to poll its status and download the file once it's done.",
        "Export एक background job के रूप में चलता है। इसे यहाँ submit करें, फिर status जानने के लिए Job ID का उपयोग करें और पूरा होने पर file डाउनलोड करें।",
        "Export एक background job म्हणून चालते. ते येथे submit करा, नंतर status पाहण्यासाठी Job ID वापरा आणि पूर्ण झाल्यावर file डाउनलोड करा.",
        "Export ek background job ki tarah chalta hai. Ise yahan submit karein, phir status poll karne ke liye Job ID use karein aur ho jaane par file download karein.",
    ),
    "journal-export.stepsHeading": (
        "How an export job flows",
        "एक्सपोर्ट जॉब कैसे चलता है",
        "एक्सपोर्ट जॉब कसे चालते",
        "Export job kaise flow karta hai",
    ),
    "journal-export.steps.0.label": ("Configure", "कॉन्फ़िगर करें", "कॉन्फिगर करा", "Configure"),
    "journal-export.steps.0.caption": (
        "Pick year, month, book and output format.",
        "Year, month, book और output format चुनें।",
        "Year, month, book आणि output format निवडा.",
        "Year, month, book aur output format choose karein.",
    ),
    "journal-export.steps.1.label": ("Submit", "सबमिट करें", "सबमिट करा", "Submit"),
    "journal-export.steps.1.caption": (
        "Export Journals queues the job and returns a Job ID.",
        "Export Journals job को queue करता है और एक Job ID लौटाता है।",
        "Export Journals job ला queue करते आणि एक Job ID परत करते.",
        "Export Journals job ko queue karta hai aur ek Job ID return karta hai.",
    ),
    "journal-export.steps.2.label": ("Processing", "प्रोसेसिंग", "प्रोसेसिंग", "Processing"),
    "journal-export.steps.2.caption": (
        "Job runs asynchronously; status shows pending until it finishes.",
        "Job asynchronously चलता है; पूरा होने तक status pending दिखाता है।",
        "Job asynchronously चालते; पूर्ण होईपर्यंत status pending दाखवते.",
        "Job asynchronously chalta hai; finish hone tak status pending dikhata hai.",
    ),
    "journal-export.steps.3.label": ("Check Status", "स्टेटस जांचें", "स्टेटस तपासा", "Check Status"),
    "journal-export.steps.3.caption": (
        "Paste the Job ID and check status to see Done or Failed.",
        "Job ID पेस्ट करें और Done या Failed देखने के लिए status जांचें।",
        "Job ID पेस्ट करा आणि Done किंवा Failed पाहण्यासाठी status तपासा.",
        "Job ID paste karein aur Done ya Failed dekhne ke liye status check karein.",
    ),
    "journal-export.steps.4.label": ("Download", "डाउनलोड करें", "डाउनलोड करा", "Download"),
    "journal-export.steps.4.caption": (
        "Once Done, use the download link to get the file.",
        "Done होने पर, file पाने के लिए download link का उपयोग करें।",
        "Done झाल्यावर, file मिळवण्यासाठी download link वापरा.",
        "Done ho jaane par, file paane ke liye download link use karein.",
    ),
    "journal-export.fieldRules.0.name": ("Year", "वर्ष", "वर्ष", "Year"),
    "journal-export.fieldRules.0.description": (
        "Calendar year of the period whose journal entries get exported.",
        "उस period का calendar year जिसकी journal entries export की जाती हैं।",
        "ज्या period च्या journal entries export केल्या जातात त्याचे calendar year.",
        "Us period ka calendar year jiski journal entries export hoti hain.",
    ),
    "journal-export.fieldRules.1.name": ("Book", "बुक", "बुक", "Book"),
    "journal-export.fieldRules.1.description": (
        "Accounting standard the entries are drawn from: Companies Act, Income Tax or Ind AS.",
        "वह accounting standard जिससे entries ली जाती हैं: Companies Act, Income Tax या Ind AS।",
        "ज्या accounting standard मधून entries घेतल्या जातात: Companies Act, Income Tax किंवा Ind AS.",
        "Wo accounting standard jisse entries li jaati hain: Companies Act, Income Tax ya Ind AS.",
    ),
    "journal-export.fieldRules.2.name": ("Format", "फ़ॉर्मेट", "फॉरमॅट", "Format"),
    "journal-export.fieldRules.2.description": (
        "Output file shape — CSV, Tally XML, PFMS XML (government) or SAP CSV — matched to your target system.",
        "Output file का प्रकार — CSV, Tally XML, PFMS XML (government) या SAP CSV — जो आपके target system से मेल खाता हो।",
        "Output file चा प्रकार — CSV, Tally XML, PFMS XML (government) किंवा SAP CSV — जो तुमच्या target system शी जुळतो.",
        "Output file ka shape — CSV, Tally XML, PFMS XML (government) ya SAP CSV — jo aapke target system se match kare.",
    ),
    "journal-export.fieldRules.3.name": ("Job ID", "जॉब आईडी", "जॉब आयडी", "Job ID"),
    "journal-export.fieldRules.3.description": (
        "Identifies a submitted export; required to check its status or reach the download link.",
        "किसी submitted export की पहचान करता है; इसका status जांचने या download link तक पहुँचने के लिए आवश्यक है।",
        "एखाद्या submitted export ची ओळख करते; त्याचा status तपासण्यासाठी किंवा download link पर्यंत पोहोचण्यासाठी आवश्यक आहे.",
        "Ek submitted export ko identify karta hai; iska status check karne ya download link tak pahunchne ke liye zaroori hai.",
    ),
    "journal-export.tip.title": (
        "Save the Job ID",
        "Job ID सेव करें",
        "Job ID सेव्ह करा",
        "Job ID save kar lein",
    ),
    "journal-export.tip.body": (
        "The Job ID box only auto-fills right after you submit an export — it isn't stored anywhere. Navigate away before the job finishes and you'll need to paste that ID back in by hand to check status or download later, so copy it somewhere safe.",
        "Job ID box केवल export submit करने के तुरंत बाद auto-fill होता है — यह कहीं भी stored नहीं है। यदि job पूरा होने से पहले आप कहीं और चले जाते हैं, तो बाद में status जांचने या download करने के लिए आपको वह ID हाथ से वापस paste करनी होगी, इसलिए इसे कहीं सुरक्षित रूप से कॉपी कर लें।",
        "Job ID box फक्त export submit केल्यानंतर लगेच auto-fill होते — ते कुठेही stored नसते. Job पूर्ण होण्यापूर्वी तुम्ही दुसरीकडे गेलात, तर नंतर status तपासण्यासाठी किंवा download करण्यासाठी ती ID हाताने परत paste करावी लागेल, म्हणून ती कुठेतरी सुरक्षित ठिकाणी कॉपी करून ठेवा.",
        "Job ID box sirf export submit karne ke turant baad auto-fill hota hai — ye kahin bhi store nahi hota. Job finish hone se pehle agar aap navigate away kar dete hain, to baad mein status check karne ya download karne ke liye aapko wo ID haath se wapas paste karni hogi, isliye ise kahin safe jagah copy kar lein.",
    ),
}


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 JOURNAL_EXPORT.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(JOURNAL_EXPORT)} journal-export keys.")


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