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

Usage: docker compose exec api python seed_translations_pageinfo_depreciation_run_wizard.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)
DEPRECIATION_RUN_WIZARD = {
    "depreciation-run-wizard.title": (
        "Depreciation Run",
        "डेप्रिसिएशन रन",
        "डेप्रिसिएशन रन",
        "Depreciation Run",
    ),
    "depreciation-run-wizard.body.0": (
        "Run three-book depreciation for a monthly period.",
        "एक मासिक अवधि के लिए three-book डेप्रिसिएशन रन करें।",
        "एका मासिक कालावधीसाठी three-book डेप्रिसिएशन रन करा.",
        "Ek monthly period ke liye three-book depreciation run karein.",
    ),
    "depreciation-run-wizard.body.1": (
        "Idempotent — re-running the same period recalculates and overwrites entries.",
        "Idempotent — वही period दोबारा run करने पर entries की दोबारा गणना होकर वे overwrite हो जाती हैं।",
        "Idempotent — तोच period पुन्हा run केल्यास entries ची पुन्हा गणना होऊन त्या overwrite होतात.",
        "Idempotent hai — same period ko dobara run karne par entries recalculate hoke overwrite ho jaati hain.",
    ),
    "depreciation-run-wizard.stepsHeading": (
        "How a run works",
        "रन कैसे काम करता है",
        "रन कसे कार्य करते",
        "Run kaise kaam karta hai",
    ),
    "depreciation-run-wizard.steps.0.label": (
        "Select Period",
        "अवधि चुनें",
        "कालावधी निवडा",
        "Period select karein",
    ),
    "depreciation-run-wizard.steps.0.caption": (
        "Pick the fiscal year and month to depreciate.",
        "डेप्रिसिएट करने के लिए fiscal year और month चुनें।",
        "डेप्रिसिएट करण्यासाठी fiscal year आणि month निवडा.",
        "Depreciate karne ke liye fiscal year aur month pick karein.",
    ),
    "depreciation-run-wizard.steps.1.label": (
        "Run Batch",
        "बैच रन करें",
        "बॅच रन करा",
        "Batch run karein",
    ),
    "depreciation-run-wizard.steps.1.caption": (
        "Calculates 3-book depreciation entries per Depreciation Master rates.",
        "Depreciation Master की दरों के अनुसार 3-book डेप्रिसिएशन entries की गणना करता है।",
        "Depreciation Master च्या दरांनुसार 3-book डेप्रिसिएशन entries ची गणना करते.",
        "Depreciation Master ki rates ke hisaab se 3-book depreciation entries calculate karta hai.",
    ),
    "depreciation-run-wizard.steps.2.label": (
        "Review Result",
        "परिणाम की समीक्षा करें",
        "निकालाचे पुनरावलोकन करा",
        "Result review karein",
    ),
    "depreciation-run-wizard.steps.2.caption": (
        "JSON summary confirms entries created; net book value updates automatically.",
        "JSON summary बनाई गई entries की पुष्टि करती है; net book value अपने आप अपडेट हो जाती है।",
        "JSON summary तयार झालेल्या entries ची पुष्टी करते; net book value आपोआप अपडेट होते.",
        "JSON summary confirm karti hai ki entries create ho gayi hain; net book value automatically update ho jaati hai.",
    ),
    "depreciation-run-wizard.steps.3.label": (
        "Reverse (optional)",
        "रिवर्स करें (वैकल्पिक)",
        "रिव्हर्स करा (ऐच्छिक)",
        "Reverse karein (optional)",
    ),
    "depreciation-run-wizard.steps.3.caption": (
        "Deletes that period's entries so you can fix data and re-run.",
        "उस period की entries को डिलीट कर देता है ताकि आप data ठीक करके दोबारा run कर सकें।",
        "त्या period च्या entries डिलीट करते जेणेकरून तुम्ही data दुरुस्त करून पुन्हा run करू शकाल.",
        "Us period ki entries delete kar deta hai taaki aap data fix karke dobara run kar sakein.",
    ),
    "depreciation-run-wizard.fieldRules.0.name": (
        "Year",
        "वर्ष",
        "वर्ष",
        "Year",
    ),
    "depreciation-run-wizard.fieldRules.0.description": (
        "Calendar year of the fiscal period to run or reverse.",
        "रन या रिवर्स करने वाली fiscal period का calendar year।",
        "रन किंवा रिव्हर्स करायच्या fiscal period चे calendar year.",
        "Jis fiscal period ko run ya reverse karna hai uska calendar year.",
    ),
    "depreciation-run-wizard.fieldRules.1.name": (
        "Month",
        "माह",
        "महिना",
        "Month",
    ),
    "depreciation-run-wizard.fieldRules.1.description": (
        "Combined with Year into a YYYY-MM period key sent to the run/reverse APIs.",
        "Year के साथ मिलकर यह एक YYYY-MM period key बनाता है, जो run/reverse APIs को भेजी जाती है।",
        "Year सोबत एकत्र येऊन हे YYYY-MM period key तयार करते, जे run/reverse APIs ला पाठवले जाते.",
        "Year ke saath combine hokar ye ek YYYY-MM period key banata hai, jo run/reverse APIs ko bheji jaati hai.",
    ),
    "depreciation-run-wizard.fieldRules.2.name": (
        "Reverse Year/Month",
        "रिवर्स वर्ष/माह",
        "रिव्हर्स वर्ष/महिना",
        "Reverse Year/Month",
    ),
    "depreciation-run-wizard.fieldRules.2.description": (
        "Separate period selector for reversal — must be an open (not yet closed) fiscal period.",
        "रिवर्सल के लिए अलग period selector — यह एक open (अभी तक बंद न हुई) fiscal period होनी चाहिए।",
        "रिव्हर्सलसाठी वेगळा period selector — ही एक open (अद्याप बंद न झालेली) fiscal period असावी लागते.",
        "Reversal ke liye alag period selector — ye ek open (abhi tak close nahi hui) fiscal period honi chahiye.",
    ),
    "depreciation-run-wizard.tip.title": (
        "Not a full undo, and only works on open periods",
        "यह पूरी तरह undo नहीं है, और केवल open periods पर काम करता है",
        "हे पूर्णपणे undo नाही, आणि फक्त open periods वर काम करते",
        "Ye pura undo nahi hai, aur sirf open periods par kaam karta hai",
    ),
    "depreciation-run-wizard.tip.body": (
        "Reverse deletes all books' depreciation_entries for that period rather than restoring prior values, and is blocked once the fiscal period is closed — reopen it in Fiscal Periods first. To run all 12 months of a fiscal year at once, use Depreciation Master instead of stepping through each month here.",
        "Reverse पिछले values को restore करने के बजाय उस period के लिए सभी books की depreciation_entries को डिलीट कर देता है, और एक बार fiscal period बंद हो जाने पर यह ब्लॉक हो जाता है — पहले इसे Fiscal Periods में दोबारा खोलें। किसी fiscal year के सभी 12 महीनों को एक साथ रन करने के लिए, यहाँ हर महीने से गुज़रने के बजाय Depreciation Master का उपयोग करें।",
        "Reverse आधीच्या values पुनर्संचयित करण्याऐवजी त्या period साठी सर्व books च्या depreciation_entries डिलीट करते, आणि fiscal period बंद झाल्यावर ते ब्लॉक होते — आधी ते Fiscal Periods मध्ये पुन्हा उघडा. एखाद्या fiscal year च्या सर्व 12 महिन्यांसाठी एकाच वेळी रन करायचे असल्यास, येथे प्रत्येक महिन्यातून जाण्याऐवजी Depreciation Master वापरा.",
        "Reverse prior values restore karne ke bajaye us period ke liye sabhi books ki depreciation_entries delete kar deta hai, aur fiscal period close hone ke baad ye block ho jaata hai — pehle ise Fiscal Periods mein reopen karein. Kisi fiscal year ke saare 12 months ek saath run karne ke liye, yahan har month step-by-step karne ke bajaye Depreciation Master use karein.",
    ),
}


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 DEPRECIATION_RUN_WIZARD.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(DEPRECIATION_RUN_WIZARD)} depreciation-run-wizard keys.")


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