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

Usage: docker compose exec api python seed_translations_pageinfo_tax_masters.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)
TAX_MASTERS = {
    "tax-masters.title": (
        "Tax Masters",
        "टैक्स मास्टर",
        "टॅक्स मास्टर",
        "Tax Masters",
    ),
    "tax-masters.subtitle": (
        "How GST rates and HSN/SAC codes are used",
        "GST दरों और HSN/SAC कोड का उपयोग कैसे किया जाता है",
        "GST दर आणि HSN/SAC कोड कसे वापरले जातात",
        "GST rates aur HSN/SAC codes kaise use hote hain",
    ),
    "tax-masters.body.0": (
        "GST rate slabs and HSN/SAC code lookups.",
        "GST दर स्लैब और HSN/SAC कोड लुकअप।",
        "GST दर स्लॅब आणि HSN/SAC कोड लूकअप.",
        "GST rate slabs aur HSN/SAC code lookups.",
    ),
    "tax-masters.body.1": (
        "Read-only — maintained via GSTN sync (Financial Masters page), not edited here.",
        "केवल पठनीय (Read-only) — GSTN sync (Financial Masters पेज) के ज़रिए मेंटेन किया जाता है, यहाँ edit नहीं किया जाता।",
        "फक्त वाचनीय (Read-only) — GSTN sync (Financial Masters पेज) द्वारे मेंटेन केले जाते, इथे edit केले जात नाही.",
        "Read-only hai — GSTN sync (Financial Masters page) ke through maintain hota hai, yahan edit nahi hota.",
    ),
    "tax-masters.stepsHeading": (
        "How GST data is used",
        "GST डेटा का उपयोग कैसे होता है",
        "GST डेटा कसा वापरला जातो",
        "GST data kaise use hota hai",
    ),
    "tax-masters.steps.0.label": ("HSN / SAC Code", "HSN / SAC कोड", "HSN / SAC कोड", "HSN / SAC Code"),
    "tax-masters.steps.0.caption": (
        "Classifies the good or service",
        "वस्तु या सेवा को वर्गीकृत करता है",
        "वस्तू किंवा सेवेचे वर्गीकरण करते",
        "Good ya service ko classify karta hai",
    ),
    "tax-masters.steps.1.label": ("GST Rate Slab", "GST दर स्लैब", "GST दर स्लॅब", "GST Rate Slab"),
    "tax-masters.steps.1.caption": (
        "CGST + SGST + IGST % linked to it",
        "इससे जुड़े CGST + SGST + IGST %",
        "याच्याशी जोडलेले CGST + SGST + IGST %",
        "Isse linked CGST + SGST + IGST %",
    ),
    "tax-masters.steps.2.label": ("Synced, Not Edited", "सिंक किया गया, एडिट नहीं", "सिंक केलेले, एडिट केलेले नाही", "Synced, Edit Nahi Hota"),
    "tax-masters.steps.2.caption": (
        "Populated from GSTN via Financial Masters",
        "Financial Masters के ज़रिए GSTN से भरा जाता है",
        "Financial Masters द्वारे GSTN वरून भरले जाते",
        "Financial Masters ke through GSTN se populate hota hai",
    ),
    "tax-masters.steps.3.label": ("Applied on Documents", "दस्तावेज़ों पर लागू", "दस्तऐवजांवर लागू", "Documents Par Apply Hota Hai"),
    "tax-masters.steps.3.caption": (
        "Used automatically on PR/PO/invoice GST lines",
        "PR/PO/invoice की GST लाइनों पर स्वचालित रूप से उपयोग होता है",
        "PR/PO/invoice च्या GST लाईन्सवर आपोआप वापरले जाते",
        "PR/PO/invoice ki GST lines par automatically use hota hai",
    ),
    "tax-masters.fieldRules.0.name": ("HSN / SAC", "HSN / SAC", "HSN / SAC", "HSN / SAC"),
    "tax-masters.fieldRules.0.description": (
        "Classification code — HSN for goods, SAC for services. A rate row carries one or the other, never both.",
        "वर्गीकरण कोड — वस्तुओं के लिए HSN, सेवाओं के लिए SAC। एक rate row में इनमें से कोई एक होता है, दोनों कभी नहीं।",
        "वर्गीकरण कोड — वस्तूंसाठी HSN, सेवांसाठी SAC. एका rate row मध्ये यापैकी एकच असते, दोन्ही कधीच नाही.",
        "Classification code hai — goods ke liye HSN, services ke liye SAC. Ek rate row mein inmein se koi ek hota hai, dono kabhi nahi.",
    ),
    "tax-masters.fieldRules.1.name": ("CGST % / SGST %", "CGST % / SGST %", "CGST % / SGST %", "CGST % / SGST %"),
    "tax-masters.fieldRules.1.description": (
        "Applied together for intra-state transactions (buyer and seller in the same state).",
        "इंट्रा-स्टेट transactions (जब buyer और seller एक ही राज्य में हों) के लिए एक साथ लागू होते हैं।",
        "इंट्रा-स्टेट transactions साठी (buyer आणि seller एकाच राज्यात असताना) एकत्र लागू होतात.",
        "Intra-state transactions ke liye (jab buyer aur seller same state mein hon) saath mein apply hote hain.",
    ),
    "tax-masters.fieldRules.2.name": ("IGST %", "IGST %", "IGST %", "IGST %"),
    "tax-masters.fieldRules.2.description": (
        "Applied instead of CGST+SGST for inter-state transactions.",
        "इंटर-स्टेट transactions के लिए CGST+SGST की जगह लागू होता है।",
        "इंटर-स्टेट transactions साठी CGST+SGST ऐवजी लागू होते.",
        "Inter-state transactions ke liye CGST+SGST ki jagah apply hota hai.",
    ),
    "tax-masters.fieldRules.3.name": ("Status", "स्थिति", "स्थिती", "Status"),
    "tax-masters.fieldRules.3.description": (
        "Only Active rates and codes are offered when GST is computed on PR/PO/invoice lines elsewhere.",
        "जब कहीं और PR/PO/invoice लाइनों पर GST की गणना की जाती है, तो केवल Active rates और codes ही उपलब्ध कराए जाते हैं।",
        "इतरत्र PR/PO/invoice लाईन्सवर GST मोजले जाते तेव्हा फक्त Active rates आणि codes दिले जातात.",
        "Jab kahin aur PR/PO/invoice lines par GST calculate hota hai, tab sirf Active rates aur codes hi offer kiye jaate hain.",
    ),
    "tax-masters.tip.title": (
        "This page is read-only",
        "यह पेज केवल पठनीय (Read-only) है",
        "हे पेज फक्त वाचनीय (Read-only) आहे",
        "Ye page read-only hai",
    ),
    "tax-masters.tip.body": (
        "GST rates and HSN/SAC codes come from GSTN via the sync on the Financial Masters page — there's no add/edit control here. If a rate looks wrong, fix it there. This page only searches: type at least one character in the HSN/SAC box, then press Enter or Search.",
        "GST rates और HSN/SAC codes, Financial Masters पेज पर sync के ज़रिए GSTN से आते हैं — यहाँ कोई add/edit control नहीं है। अगर कोई rate गलत लगे, तो उसे वहीं ठीक करें। यह पेज केवल search करता है: HSN/SAC बॉक्स में कम से कम एक character टाइप करें, फिर Enter दबाएँ या Search पर क्लिक करें।",
        "GST rates आणि HSN/SAC codes, Financial Masters पेजवरील sync द्वारे GSTN वरून येतात — इथे कोणतेही add/edit control नाही. एखादा rate चुकीचा वाटल्यास, तो तिथे दुरुस्त करा. हे पेज फक्त search करते: HSN/SAC बॉक्समध्ये किमान एक character टाईप करा, नंतर Enter दाबा किंवा Search वर क्लिक करा.",
        "GST rates aur HSN/SAC codes, Financial Masters page par sync ke through GSTN se aate hain — yahan koi add/edit control nahi hai. Agar koi rate galat lage, to use wahin fix karein. Ye page sirf search karta hai: HSN/SAC box mein kam se kam ek character type karein, phir Enter dabayein ya Search par click 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 TAX_MASTERS.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(TAX_MASTERS)} tax-masters keys.")


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