"""One-off seed: registers translation_keys English source_text and hi/mr/hinglish
translation_values for 55 Reports UI strings (Budget Allocation Report, Rental Income
Report, PO-wise Asset Report) that were already wrapped in t(key, fallback) calls in
the code but never seeded — so hi/mr/hinglish users were seeing raw English.

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

# key -> (english, hi, mr, hinglish)
REPORTS_GAP_BATCH3 = {
    # --- Budget Allocation Report ---
    "reports.budgetAlloc.allYears": ("All Years", "सभी वर्ष", "सर्व वर्षे", "Sabhi Years"),
    "reports.budgetAlloc.assets": ("assets", "assets", "assets", "assets"),
    "reports.budgetAlloc.budgets": ("Budget Lines", "Budget Lines", "Budget Lines", "Budget Lines"),
    "reports.budgetAlloc.colActions": ("Actions", "कार्रवाई", "कृती", "Actions"),
    "reports.budgetAlloc.colActual": ("Spent", "खर्च", "खर्च", "Spent"),
    "reports.budgetAlloc.colApproved": ("Approved", "स्वीकृत", "मंजूर", "Approved"),
    "reports.budgetAlloc.colAssets": ("Assets", "Assets", "Assets", "Assets"),
    "reports.budgetAlloc.colAvailable": ("Available", "उपलब्ध", "उपलब्ध", "Available"),
    "reports.budgetAlloc.colCC": ("Cost Centre", "Cost Centre", "Cost Centre", "Cost Centre"),
    "reports.budgetAlloc.colFY": ("Fiscal Year", "Fiscal Year", "Fiscal Year", "Fiscal Year"),
    "reports.budgetAlloc.colHead": ("Budget Head", "Budget Head", "Budget Head", "Budget Head"),
    "reports.budgetAlloc.colPOs": ("POs", "POs", "POs", "POs"),
    "reports.budgetAlloc.colStatus": ("Status", "स्थिति", "स्थिती", "Status"),
    "reports.budgetAlloc.empty": (
        "No budget lines for this filter.",
        "इस filter के लिए कोई budget line नहीं है।",
        "या filter साठी कोणतीही budget line नाही.",
        "Is filter ke liye koi budget line nahi hai.",
    ),
    "reports.budgetAlloc.filterFY": ("Fiscal Year", "Fiscal Year", "Fiscal Year", "Fiscal Year"),
    "reports.budgetAlloc.itemAmount": ("Amount", "राशि", "रक्कम", "Amount"),
    "reports.budgetAlloc.itemDate": ("Date", "दिनांक", "दिनांक", "Date"),
    "reports.budgetAlloc.itemKind": ("Type", "प्रकार", "प्रकार", "Type"),
    "reports.budgetAlloc.itemName": ("Name", "नाम", "नाव", "Name"),
    "reports.budgetAlloc.itemRef": ("Reference", "संदर्भ", "संदर्भ", "Reference"),
    "reports.budgetAlloc.itemStatus": ("Status", "स्थिति", "स्थिती", "Status"),
    "reports.budgetAlloc.loadFailed": (
        "Failed to load budget allocation report.",
        "Budget allocation report लोड करने में विफल।",
        "Budget allocation report लोड करण्यात अयशस्वी.",
        "Budget allocation report load karne mein fail ho gaya.",
    ),
    "reports.budgetAlloc.loading": (
        "Loading report...",
        "रिपोर्ट लोड हो रही है...",
        "अहवाल लोड होत आहे...",
        "Report load ho raha hai...",
    ),
    "reports.budgetAlloc.loadingItems": (
        "Loading items...",
        "आइटम लोड हो रहे हैं...",
        "आयटम्स लोड होत आहेत...",
        "Items load ho rahe hain...",
    ),
    "reports.budgetAlloc.noItems": (
        "No POs or assets funded by this budget yet.",
        "इस budget से अभी तक कोई PO या asset funded नहीं है।",
        "या budget मधून अजून कोणतीही PO किंवा asset funded नाही.",
        "Is budget se abhi tak koi PO ya asset funded nahi hai.",
    ),
    "reports.budgetAlloc.pos": ("POs", "POs", "POs", "POs"),
    "reports.budgetAlloc.run": ("Run Report", "Report चलाएं", "Report चालवा", "Report Run Karein"),
    "reports.budgetAlloc.totalActual": ("Total Spent", "कुल खर्च", "एकूण खर्च", "Total Spent"),
    "reports.budgetAlloc.totalApproved": ("Total Approved", "कुल स्वीकृत", "एकूण मंजूर", "Total Approved"),
    "reports.budgetAlloc.totalAvailable": ("Total Available", "कुल उपलब्ध", "एकूण उपलब्ध", "Total Available"),
    "reports.budgetAlloc.totalCommitted": ("Total Committed", "कुल प्रतिबद्ध", "एकूण वचनबद्ध", "Total Committed"),
    "reports.budgetAlloc.viewItems": ("View items", "View items", "View items", "View items"),

    # --- PO-wise Asset Report ---
    "reports.poWise.choosePO": (
        "Choose a Purchase Order…",
        "एक Purchase Order चुनें…",
        "एक Purchase Order निवडा…",
        "Ek Purchase Order choose karein…",
    ),
    "reports.poWise.selectPO": ("Purchase Order", "Purchase Order", "Purchase Order", "Purchase Order"),
    "reports.poWise.subtitle": (
        "Select a Purchase Order to see the assets bought under it, their current lifecycle state and custodian.",
        "इसके अंतर्गत खरीदी गई assets, उनकी current lifecycle state और custodian देखने के लिए एक Purchase Order चुनें।",
        "याअंतर्गत खरेदी केलेल्या assets, त्यांची current lifecycle state आणि custodian पाहण्यासाठी एक Purchase Order निवडा.",
        "Iske under khareedi gayi assets, unki current lifecycle state aur custodian dekhne ke liye ek Purchase Order select karein.",
    ),

    # --- Rental Income Report ---
    "reports.rentalIncome.col.assetRef": ("Asset Ref", "Asset Ref", "Asset Ref", "Asset Ref"),
    "reports.rentalIncome.col.due": ("Amount Due", "देय राशि", "देय रक्कम", "Amount Due"),
    "reports.rentalIncome.col.name": ("Asset Name", "Asset का नाम", "Asset चे नाव", "Asset Name"),
    "reports.rentalIncome.col.period": ("Period", "Period", "Period", "Period"),
    "reports.rentalIncome.col.received": ("Amount Received", "प्राप्त राशि", "प्राप्त रक्कम", "Amount Received"),
    "reports.rentalIncome.col.renter": ("Renter", "Renter", "Renter", "Renter"),
    "reports.rentalIncome.empty": (
        "No rental income entries recorded for this fiscal year yet.",
        "इस fiscal year के लिए अभी तक कोई rental income entry दर्ज नहीं हुई है।",
        "या fiscal year साठी अजून कोणतीही rental income entry नोंदवली गेलेली नाही.",
        "Is fiscal year ke liye abhi tak koi rental income entry record nahi hui hai.",
    ),
    "reports.rentalIncome.entryCount": ("Entries", "प्रविष्टियाँ", "नोंदी", "Entries"),
    "reports.rentalIncome.fiscalYear": ("Fiscal Year", "Fiscal Year", "Fiscal Year", "Fiscal Year"),
    "reports.rentalIncome.generate": (
        "Generate Period Entries",
        "Period Entries जनरेट करें",
        "Period Entries जनरेट करा",
        "Period Entries Generate Karein",
    ),
    "reports.rentalIncome.generateDesc": (
        "Idempotent — re-running the same period recalculates due amounts without touching any already-recorded payment.",
        "Idempotent — वही period दोबारा run करने पर due राशियों की दोबारा गणना होती है, बिना किसी पहले से दर्ज payment को छुए।",
        "Idempotent — तोच period पुन्हा run केल्यास due रकमांची पुन्हा गणना होते, आधीच नोंदवलेल्या कोणत्याही payment ला स्पर्श न करता.",
        "Idempotent — same period ko dobara run karne par due amounts recalculate ho jaate hain, bina kisi already-recorded payment ko touch kiye.",
    ),
    "reports.rentalIncome.loading": ("Loading…", "लोड हो रहा है…", "लोड होत आहे…", "Loading ho raha hai…"),
    "reports.rentalIncome.monthLabel": ("Month", "महीना", "महिना", "Month"),
    "reports.rentalIncome.runBtn": (
        "Run Rental Income",
        "Rental Income चलाएं",
        "Rental Income चालवा",
        "Rental Income Run Karein",
    ),
    "reports.rentalIncome.runError": (
        "Rental income run failed.",
        "Rental income run विफल हुआ।",
        "Rental income run अयशस्वी झाला.",
        "Rental income run fail ho gaya.",
    ),
    "reports.rentalIncome.running": ("Running...", "चल रहा है...", "सुरू आहे...", "Chal raha hai..."),
    "reports.rentalIncome.subtitle": (
        "Income entries recorded against rental agreements, by fiscal year.",
        "Fiscal year के अनुसार rental agreements के विरुद्ध दर्ज income entries।",
        "Fiscal year नुसार rental agreements विरुद्ध नोंदवलेल्या income entries.",
        "Fiscal year ke hisaab se rental agreements ke against record ki gayi income entries.",
    ),
    "reports.rentalIncome.totalDue": ("Total Due", "कुल देय", "एकूण देय", "Total Due"),
    "reports.rentalIncome.totalReceived": ("Total Received", "कुल प्राप्त", "एकूण प्राप्त", "Total Received"),
    "reports.rentalIncome.yearLabel": ("Year", "वर्ष", "वर्ष", "Year"),
}


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 REPORTS_GAP_BATCH3.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(REPORTS_GAP_BATCH3)} reports-gap-batch3 keys.")


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