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

Usage: docker compose exec api python seed_translations_pageinfo_asset_appreciation.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)
ASSET_APPRECIATION = {
    "asset-appreciation.title": (
        "Asset Appreciation",
        "Asset मूल्यवृद्धि",
        "Asset मूल्यवाढ",
        "Asset Appreciation",
    ),
    "asset-appreciation.subtitle": (
        "Upward revaluation for gaining asset classes",
        "मूल्यवृद्धि वाली asset classes के लिए ऊपर की ओर revaluation",
        "मूल्यवाढ होणाऱ्या asset classes साठी वरच्या दिशेने revaluation",
        "Gaining asset classes ke liye upward revaluation",
    ),
    "asset-appreciation.body.0": (
        "Record capital appreciation for asset classes expected to gain value over time, such as Land or Investment Property.",
        "उन asset classes के लिए capital appreciation दर्ज करें जिनसे समय के साथ मूल्य बढ़ने की उम्मीद है, जैसे Land या Investment Property।",
        "ज्या asset classes चे मूल्य कालांतराने वाढण्याची अपेक्षा आहे, जसे की Land किंवा Investment Property, त्यांच्यासाठी capital appreciation नोंदवा.",
        "Un asset classes ke liye capital appreciation record karein jinke value time ke saath badhne ki ummeed hai, jaise Land ya Investment Property.",
    ),
    "asset-appreciation.body.1": (
        "Uses the same revaluation record as Asset Revaluation, restricted to upward moves.",
        "यह Asset Revaluation जैसा ही revaluation record उपयोग करता है, लेकिन केवल ऊपर की ओर होने वाले बदलावों तक सीमित है।",
        "हे Asset Revaluation प्रमाणेच revaluation record वापरते, पण फक्त वरच्या दिशेने होणाऱ्या बदलांपुरते मर्यादित आहे.",
        "Ye Asset Revaluation jaisa hi revaluation record use karta hai, bas sirf upward moves tak restricted hai.",
    ),
    "asset-appreciation.stepsHeading": (
        "How a record flows",
        "Record कैसे flow होता है",
        "Record कसा flow होतो",
        "Record kaise flow hota hai",
    ),
    "asset-appreciation.steps.0.label": ("Select Asset", "Asset चुनें", "Asset निवडा", "Asset select karein"),
    "asset-appreciation.steps.0.caption": (
        "List is pre-filtered to appreciating asset classes only.",
        "List पहले से केवल appreciating asset classes तक filter की गई है।",
        "List आधीच फक्त appreciating asset classes पुरती filter केलेली आहे.",
        "List pehle se sirf appreciating asset classes tak filter ki hui hai.",
    ),
    "asset-appreciation.steps.1.label": ("Enter New Value", "New Value दर्ज करें", "New Value टाका", "New Value enter karein"),
    "asset-appreciation.steps.1.caption": (
        "Must be strictly higher than the current value shown above.",
        "यह ऊपर दिखाए गए current value से सख्ती से अधिक होना चाहिए।",
        "हे वर दाखवलेल्या current value पेक्षा काटेकोरपणे जास्त असले पाहिजे.",
        "Ye upar dikhaye gaye current value se strictly zyada hona chahiye.",
    ),
    "asset-appreciation.steps.2.label": ("Review Gain", "Gain की समीक्षा करें", "Gain चा आढावा घ्या", "Gain review karein"),
    "asset-appreciation.steps.2.caption": (
        "Projected gain updates live as you type the new value.",
        "जैसे ही आप new value टाइप करते हैं, projected gain live update होता है।",
        "तुम्ही new value टाइप करताच, projected gain live update होतो.",
        "Jaise hi aap new value type karte hain, projected gain live update hota hai.",
    ),
    "asset-appreciation.steps.3.label": ("Record", "Record करें", "Record करा", "Record karein"),
    "asset-appreciation.steps.3.caption": (
        "Posts a revaluation entry and clears the form for the next asset.",
        "यह एक revaluation entry post करता है और अगले asset के लिए form को clear कर देता है।",
        "हे एक revaluation entry post करते आणि पुढच्या asset साठी form clear करते.",
        "Ye ek revaluation entry post karta hai aur next asset ke liye form clear kar deta hai.",
    ),
    "asset-appreciation.fieldRules.0.name": ("Asset", "Asset", "Asset", "Asset"),
    "asset-appreciation.fieldRules.0.description": (
        "Only assets whose asset class is flagged as appreciating (e.g. Land, Investment Property) are listed.",
        "केवल वे assets सूचीबद्ध होते हैं जिनकी asset class को appreciating के रूप में flag किया गया है (जैसे Land, Investment Property)।",
        "फक्त त्याच assets सूचीबद्ध होतात ज्यांची asset class appreciating म्हणून flag केलेली आहे (उदा. Land, Investment Property).",
        "Sirf wahi assets list hote hain jinki asset class appreciating flag ki gayi hai (jaise Land, Investment Property).",
    ),
    "asset-appreciation.fieldRules.1.name": ("Appreciation Date", "Appreciation Date", "Appreciation Date", "Appreciation Date"),
    "asset-appreciation.fieldRules.1.description": (
        "Effective date recorded on the revaluation entry.",
        "revaluation entry पर दर्ज की गई प्रभावी तिथि।",
        "revaluation entry वर नोंदवलेली प्रभावी तारीख.",
        "Revaluation entry par record hui effective date.",
    ),
    "asset-appreciation.fieldRules.2.name": ("New Value", "New Value", "New Value", "New Value"),
    "asset-appreciation.fieldRules.2.description": (
        "Must be a positive number greater than the current value — a lower value is rejected and points you to Asset Revaluation instead.",
        "यह current value से अधिक एक positive number होना चाहिए — कम value होने पर इसे reject कर दिया जाता है और आपको इसके बजाय Asset Revaluation पर भेजा जाता है।",
        "हे current value पेक्षा जास्त असलेला positive number असला पाहिजे — कमी value असल्यास ती reject केली जाते आणि त्याऐवजी तुम्हाला Asset Revaluation कडे निर्देशित केले जाते.",
        "Ye current value se zyada ek positive number hona chahiye — kam value hone par reject ho jaata hai aur aapko iske bajaye Asset Revaluation par point kiya jaata hai.",
    ),
    "asset-appreciation.fieldRules.3.name": ("Basis", "Basis", "Basis", "Basis"),
    "asset-appreciation.fieldRules.3.description": (
        "Market Value, Replacement Cost, or Indexation Method — sent to the backend as fair_value or cost.",
        "Market Value, Replacement Cost, या Indexation Method — इसे backend को fair_value या cost के रूप में भेजा जाता है।",
        "Market Value, Replacement Cost, किंवा Indexation Method — हे backend कडे fair_value किंवा cost म्हणून पाठवले जाते.",
        "Market Value, Replacement Cost, ya Indexation Method — ye backend ko fair_value ya cost ke roop mein bheja jaata hai.",
    ),
    "asset-appreciation.fieldRules.4.name": ("Reason / Notes", "Reason / Notes", "Reason / Notes", "Reason / Notes"),
    "asset-appreciation.fieldRules.4.description": (
        "Optional free text, shown against the entry in the value history below.",
        "वैकल्पिक free text, जो नीचे value history में entry के सामने दिखाया जाता है।",
        "पर्यायी free text, जो खाली value history मध्ये entry समोर दाखवला जातो.",
        "Optional free text hai, jo neeche value history mein entry ke against dikhaya jaata hai.",
    ),
    "asset-appreciation.tip.title": (
        "Current Value baseline",
        "Current Value baseline",
        "Current Value baseline",
        "Current Value baseline",
    ),
    "asset-appreciation.tip.body": (
        "\"Current Value\" is not always the acquisition cost — once an asset has a prior revaluation, it's that entry's new value instead. Back-to-back appreciations compound off the last recorded value, not the original purchase price.",
        "\"Current Value\" हमेशा acquisition cost नहीं होती — एक बार किसी asset की prior revaluation हो जाने पर, यह उस entry की new value बन जाती है। लगातार होने वाली appreciations आखिरी दर्ज value पर compound होती हैं, न कि original purchase price पर।",
        "\"Current Value\" नेहमी acquisition cost नसते — एकदा एखाद्या asset ची prior revaluation झाली की, ती त्या entry ची new value बनते. सलग होणाऱ्या appreciations शेवटच्या नोंदवलेल्या value वर compound होतात, मूळ purchase price वर नाही.",
        "\"Current Value\" hamesha acquisition cost nahi hoti — ek baar kisi asset ki prior revaluation ho jaane ke baad, wo us entry ki new value ban jaati hai. Ek ke baad ek hone wali appreciations last recorded value par compound hoti hain, original purchase price par nahi.",
    ),
}


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 ASSET_APPRECIATION.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(ASSET_APPRECIATION)} asset-appreciation keys.")


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