import html
import re
import requests
from datetime import datetime
from xml.etree import ElementTree as ET

from flask import current_app
from app import db
from app.models import InvoiceItem, ProformaInvoiceItem, QuoteItem, CurrencyRateMaster


class TallyService:

    def __init__(self):
        self.tally_url = current_app.config.get("TALLY_URL", "").rstrip("/")
        self.company_name = current_app.config.get("TALLY_COMPANY_NAME")
        self.server_name = current_app.config.get("TALLY_SERVER_NAME")
        self.server_password = current_app.config.get("TALLY_SERVER_PASSWORD")
        self.use_server_params = bool(current_app.config.get("TALLY_USE_SERVER_PARAMS", False))
        self.verify_company = bool(current_app.config.get("TALLY_VERIFY_COMPANY", True))
        self.timeout = int(current_app.config.get("TALLY_TIMEOUT", 30))

        self.sales_ledger = current_app.config.get("TALLY_SALES_LEDGER", "Translation Sales")
        self.cgst_ledger = current_app.config.get("TALLY_CGST_LEDGER", "Output Payable CGST @ 9 %")
        self.sgst_ledger = current_app.config.get("TALLY_SGST_LEDGER", "Output Payable SGST @ 9 %")
        self.igst_ledger = current_app.config.get("TALLY_IGST_LEDGER", "Output Payable IGST @ 18 %")

        # Vendor invoice Journal configuration. These remain independent from
        # the existing client Sales voucher ledgers.
        self.vendor_voucher_type = current_app.config.get("TALLY_VENDOR_VOUCHER_TYPE", "Journal")
        self.vendor_expense_domestic_registered = current_app.config.get(
            "TALLY_VENDOR_EXPENSE_DOMESTIC_REGISTERED_LEDGER",
            "Translation  Expenses (Domestic)_GST_Registered_ITC",
        )
        self.vendor_expense_domestic_unregistered = current_app.config.get(
            "TALLY_VENDOR_EXPENSE_DOMESTIC_UNREGISTERED_LEDGER",
            "Translation  Expenses (Domestic)_GST_Unregistered",
        )
        self.vendor_expense_international = current_app.config.get(
            "TALLY_VENDOR_EXPENSE_INTERNATIONAL_LEDGER",
            "Translation Expenses (International)",
        )
        self.vendor_tds_ledger = current_app.config.get(
            "TALLY_VENDOR_TDS_LEDGER",
            "TDS on Professional",
        )
        self.vendor_input_igst_ledger = current_app.config.get(
            "TALLY_VENDOR_INPUT_IGST_LEDGER",
            "Input Receivable IGST @ 18%",
        )

    def esc(self, value):
        value = str(value or "").strip()
        value = value.replace("–", "-").replace("—", "-")
        value = " ".join(value.split())
        return html.escape(value)

    def money(self, value):
        return round(float(value or 0), 2)

    def esc_exact(self, value):
        """XML-escape a Tally master name without collapsing internal spaces."""
        value = str(value or "").strip()
        value = value.replace("–", "-").replace("—", "-")
        return html.escape(value)
    @staticmethod
    def normalize_currency_code(currency_code):
        """Return the canonical ISO-style currency code used by Currency Rate Master.

        Historical vendor/PMS records can contain display names such as ``EURO``
        while Currency Rate Master stores the ISO code ``EUR``.  Tally conversion
        must compare canonical codes, otherwise a valid EUR rate is incorrectly
        reported as missing.
        """
        raw = str(currency_code or "INR").strip().upper()

        aliases = {
            "EURO": "EUR",
            "EUROS": "EUR",
            "€": "EUR",
            "US DOLLAR": "USD",
            "US DOLLARS": "USD",
            "US$": "USD",
            "$": "USD",
            "POUND": "GBP",
            "POUNDS": "GBP",
            "POUND STERLING": "GBP",
            "STERLING": "GBP",
            "£": "GBP",
            "CANADIAN DOLLAR": "CAD",
            "CANADIAN DOLLARS": "CAD",
            "CA$": "CAD",
            "INDIAN RUPEE": "INR",
            "INDIAN RUPEES": "INR",
            "RUPEE": "INR",
            "RUPEES": "INR",
            "₹": "INR",
        }
        return aliases.get(raw, raw)

    def get_rate_to_inr(self, currency_code, invoice_date):
        original_currency = str(currency_code or "INR").strip().upper()
        currency_code = self.normalize_currency_code(original_currency)

        if currency_code == "INR":
            return 1

        rate = (
            CurrencyRateMaster.query
            .filter_by(
                year=invoice_date.year,
                month=invoice_date.month,
                currency_code=currency_code
            )
            .first()
        )

        if not rate:
            display_currency = (
                f"{original_currency} (mapped to {currency_code})"
                if original_currency != currency_code
                else currency_code
            )
            raise Exception(
                f"Currency rate missing for {display_currency} "
                f"{invoice_date.month}-{invoice_date.year}. "
                "Please update Currency Rate Master."
            )

        return float(rate.rate_to_inr or 1)

    def normalize_tally_name(self, value):
        value = str(value or "").strip()
        value = value.replace("–", "-").replace("—", "-")
        value = re.sub(r"\s+", " ", value)
        return value

    def get_request_params(self):
        """Return Tally gateway query parameters only when explicitly enabled."""
        if not self.use_server_params:
            return None

        params = {}
        if self.server_name:
            params["servername"] = self.server_name
        if self.server_password:
            params["password"] = self.server_password
        return params or None

    def post_to_tally(self, xml):
        if not self.tally_url:
            raise Exception("TALLY_URL is not configured.")

        current_app.logger.info(
            "Posting Tally XML to url=%r use_server_params=%r server=%r",
            self.tally_url, self.use_server_params, self.server_name
        )

        return requests.post(
            self.tally_url,
            params=self.get_request_params(),
            data=xml.encode("utf-8"),
            headers={"Content-Type": "text/xml; charset=utf-8"},
            timeout=self.timeout,
        )

    def fetch_tally_company_names(self):
        """Read company names from the exact Tally endpoint used for voucher sync."""
        xml = """
<ENVELOPE>
  <HEADER>
    <VERSION>1</VERSION>
    <TALLYREQUEST>Export</TALLYREQUEST>
    <TYPE>Collection</TYPE>
    <ID>CNCompanyList</ID>
  </HEADER>
  <BODY>
    <DESC>
      <STATICVARIABLES>
        <SVEXPORTFORMAT>$$SysName:XML</SVEXPORTFORMAT>
      </STATICVARIABLES>
      <TDL>
        <TDLMESSAGE>
          <COLLECTION NAME="CNCompanyList">
            <TYPE>Company</TYPE>
            <FETCH>Name</FETCH>
          </COLLECTION>
        </TDLMESSAGE>
      </TDL>
    </DESC>
  </BODY>
</ENVELOPE>
""".strip()

        response = self.post_to_tally(xml)
        if response.status_code != 200:
            raise Exception(
                f"Unable to read Tally companies. HTTP {response.status_code}: {response.text}"
            )

        text = response.text or ""
        names = []

        try:
            root = ET.fromstring(text)
            for node in root.iter():
                tag = str(node.tag).split("}")[-1].upper()
                if tag == "NAME" and node.text and node.text.strip():
                    names.append(node.text.strip())
        except ET.ParseError:
            names.extend(
                re.findall(r"<NAME[^>]*>(.*?)</NAME>", text, flags=re.I | re.S)
            )

        result = []
        seen = set()
        for name in names:
            clean = html.unescape(str(name)).strip()
            key = self.normalize_tally_name(clean).casefold()
            if clean and key not in seen:
                seen.add(key)
                result.append(clean)
        return result

    def match_tally_company_name(self, configured_name):
        """Return the exact company spelling supplied by the connected Tally instance."""
        if not self.verify_company:
            return configured_name

        available = self.fetch_tally_company_names()
        wanted = self.normalize_tally_name(configured_name).casefold()

        for actual in available:
            if self.normalize_tally_name(actual).casefold() == wanted:
                return actual

        displayed = ", ".join(available) if available else "No companies returned"
        raise Exception(
            f"Tally company '{configured_name}' is not available at {self.tally_url}. "
            f"Companies visible to this endpoint: {displayed}"
        )

    def resolve_tally_company_name(self, company_branch):
        """Read the latest Tally company name directly from the linked branch row."""
        branch_company_name = ""

        if company_branch is not None:
            try:
                # Force SQLAlchemy to discard any cached value and read the current
                # tally_company_name from the database.
                db.session.expire(company_branch, ["tally_company_name"])
            except Exception:
                pass

            branch_company_name = getattr(company_branch, "tally_company_name", None)

        tally_company_name = self.normalize_tally_name(
            branch_company_name or self.company_name
        )

        if not tally_company_name:
            branch_id = getattr(company_branch, "id", None)
            raise Exception(
                f"Tally company name is missing for billing branch ID {branch_id or '-'}."
            )

        exact_name = self.match_tally_company_name(tally_company_name)
        current_app.logger.info(
            "Resolved Tally company branch_id=%r configured=%r actual=%r",
            getattr(company_branch, "id", None), tally_company_name, exact_name
        )
        return exact_name

    def get_sales_ledger(self, tally_company_name):
        tally_company_name = self.normalize_tally_name(tally_company_name)

        # Do not bind the export ledger to a particular financial-year suffix.
        if "NSEZ" in tally_company_name.upper():
            return "Sales Export"

        return self.sales_ledger

    def get_party_ledger_name(self, document):
        """Resolve the customer ledger from the exact client branch used in the document.

        Branch-wise mapping is the primary source. Client-level mapping is retained only
        as a legacy fallback so older records continue to sync.
        """
        client = getattr(document, "client", None)
        client_branch = getattr(document, "client_branch", None)

        # Credit notes created from older data may not carry client_branch_id even when
        # the original invoice has it. In that case, inherit the invoice branch.
        if client_branch is None:
            invoice = getattr(document, "invoice", None)
            if invoice is not None:
                client_branch = getattr(invoice, "client_branch", None)

        branch_ledger = ""
        if client_branch is not None:
            branch_ledger = str(
                getattr(client_branch, "tally_ledger_name", None) or ""
            ).strip()

        if branch_ledger:
            return branch_ledger

        legacy_client_ledger = ""
        if client is not None:
            legacy_client_ledger = str(
                getattr(client, "tally_ledger_name", None) or ""
            ).strip()

        if legacy_client_ledger:
            return legacy_client_ledger

        client_name = (
            getattr(client, "company_name", None)
            or "the selected client"
        )

        if client_branch is not None:
            branch_name = (
                getattr(client_branch, "branch_location", None)
                or getattr(client_branch, "city", None)
                or f"Branch ID {getattr(client_branch, 'id', '')}"
            )
            raise Exception(
                f"Tally ledger is not mapped for client branch: "
                f"{client_name} - {branch_name}. "
                "Please update it from Finance > Tally Ledger Mapping."
            )

        raise Exception(
            f"Client branch is missing for {client_name}. "
            "Please select the customer branch on the invoice and map its ledger "
            "from Finance > Tally Ledger Mapping."
        )

    def build_sales_voucher_xml(self, invoice):
        quote = invoice.quote

        if not quote:
            raise Exception("Quote missing in invoice.")

        client = invoice.client
        company_branch = invoice.company_branch

        

        if not client:
            raise Exception("Client missing in invoice.")

        tally_company_name = self.resolve_tally_company_name(company_branch)
        
        sales_ledger_name = self.get_sales_ledger(tally_company_name)

        party_name = self.get_party_ledger_name(invoice)

        items = (
            invoice.items
            .order_by(InvoiceItem.sort_order.asc(), InvoiceItem.id.asc())
            .all()
        )

        if not items and invoice.pi:
            items = (
                invoice.pi.items
                .order_by(ProformaInvoiceItem.sort_order.asc(), ProformaInvoiceItem.id.asc())
                .all()
            )
        if not items:
            items = (
                quote.items
                .order_by(QuoteItem.sort_order.asc(), QuoteItem.id.asc())
                .all()
            )

        if not items:
            raise Exception("No invoice items found.")

        invoice_date = invoice.invoice_date.strftime("%Y%m%d")
        voucher_no = invoice.invoice_no

        currency_code = (invoice.currency or "INR").upper()
        rate_to_inr = self.get_rate_to_inr(currency_code, invoice.invoice_date)

        foreign_total = self.money(invoice.total_amount)
        foreign_cgst = self.money(invoice.cgst)
        foreign_sgst = self.money(invoice.sgst)
        foreign_igst = self.money(invoice.igst)

        if currency_code != "INR":
            total = self.money(foreign_total * rate_to_inr)
            cgst = self.money(foreign_cgst * rate_to_inr)
            sgst = self.money(foreign_sgst * rate_to_inr)
            igst = self.money(foreign_igst * rate_to_inr)
        else:
            total = foreign_total
            cgst = foreign_cgst
            sgst = foreign_sgst
            igst = foreign_igst

        jobcard_no = ""

        if getattr(invoice, "jobcard", None):
            jobcard_no = invoice.jobcard.jobcard_code or ""

        if not jobcard_no:
            try:
                jobcard = quote.operations_jobcards.order_by(db.desc("id")).first()
                if jobcard:
                    jobcard_no = jobcard.jobcard_code or ""
            except Exception:
                pass


        narration = f"Jobcard: {jobcard_no or '-'}"

        if currency_code != "INR":
            narration += (
                f" | Invoice Amount: {currency_code} {foreign_total}"
                f" | Rate: {rate_to_inr}"
                f" | INR Amount: {total}"
            )

        if invoice.irn:
            narration += f" | IRN: {invoice.irn}"

        if invoice.ack_no:
            narration += f" | Ack No: {invoice.ack_no}"


        bill_ref_no = jobcard_no or invoice.invoice_no


        party_entry_xml = f"""
        <LEDGERENTRIES.LIST>
            <LEDGERNAME>{self.esc(party_name)}</LEDGERNAME>
            <ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
            <ISPARTYLEDGER>Yes</ISPARTYLEDGER>
            <AMOUNT>-{total}</AMOUNT>

            <BILLALLOCATIONS.LIST>
                <NAME>{self.esc(bill_ref_no)}</NAME>
                <BILLTYPE>New Ref</BILLTYPE>
                <AMOUNT>-{total}</AMOUNT>
            </BILLALLOCATIONS.LIST>
        </LEDGERENTRIES.LIST>
        """

        sales_amount = self.money(
            float(total or 0)
            - float(cgst or 0)
            - float(sgst or 0)
            - float(igst or 0)
        )

        sales_entry_xml = f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc(sales_ledger_name)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>No</ISPARTYLEDGER>
    <AMOUNT>{sales_amount}</AMOUNT>
</LEDGERENTRIES.LIST>
"""

        tax_xml = ""

        if cgst > 0:
            tax_xml += f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc(self.cgst_ledger)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>No</ISPARTYLEDGER>
    <AMOUNT>{cgst}</AMOUNT>
</LEDGERENTRIES.LIST>
"""

        if sgst > 0:
            tax_xml += f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc(self.sgst_ledger)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>No</ISPARTYLEDGER>
    <AMOUNT>{sgst}</AMOUNT>
</LEDGERENTRIES.LIST>
"""

        if igst > 0:
            tax_xml += f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc(self.igst_ledger)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>No</ISPARTYLEDGER>
    <AMOUNT>{igst}</AMOUNT>
</LEDGERENTRIES.LIST>
"""

        xml = f"""
<ENVELOPE>
  <HEADER>
    <TALLYREQUEST>Import Data</TALLYREQUEST>
  </HEADER>
  <BODY>
    <IMPORTDATA>
      <REQUESTDESC>
        <REPORTNAME>Vouchers</REPORTNAME>
        <STATICVARIABLES>
          <SVCURRENTCOMPANY>{self.esc(tally_company_name)}</SVCURRENTCOMPANY>
        </STATICVARIABLES>
      </REQUESTDESC>

      <REQUESTDATA>
        <TALLYMESSAGE xmlns:UDF="TallyUDF">
          <VOUCHER ACTION="Create" VCHTYPE="Sales">
            <DATE>{invoice_date}</DATE>
            <VOUCHERTYPENAME>Sales</VOUCHERTYPENAME>
            <VOUCHERNUMBER>{self.esc(voucher_no)}</VOUCHERNUMBER>
            <REFERENCE>{self.esc(bill_ref_no)}</REFERENCE>

            <PARTYLEDGERNAME>{self.esc(party_name)}</PARTYLEDGERNAME>
            <PARTYNAME>{self.esc(party_name)}</PARTYNAME>
            <BASICBASEPARTYNAME>{self.esc(party_name)}</BASICBASEPARTYNAME>

            <PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>
            <ISINVOICE>No</ISINVOICE>
            <NARRATION>{self.esc(narration)}</NARRATION>

            {party_entry_xml}
            {sales_entry_xml}
            {tax_xml}

          </VOUCHER>
        </TALLYMESSAGE>
      </REQUESTDATA>
    </IMPORTDATA>
  </BODY>
</ENVELOPE>
"""
        return xml.strip()
    
    def build_credit_note_xml(self, credit_note):

        invoice = credit_note.invoice
        client = credit_note.client
        company_branch = credit_note.company_branch

        if not client:
            raise Exception("Client missing in credit note.")

        tally_company_name = self.resolve_tally_company_name(company_branch)
        
        sales_ledger_name = self.get_sales_ledger(tally_company_name)

        party_name = self.get_party_ledger_name(credit_note)

        credit_note_date = credit_note.credit_note_date.strftime("%Y%m%d")

        voucher_no = credit_note.credit_note_no

        cgst = self.money(credit_note.cgst)
        sgst = self.money(credit_note.sgst)
        igst = self.money(credit_note.igst)

        total = self.money(credit_note.total_amount)

        sales_amount = self.money(
            float(credit_note.total_amount or 0)
            - float(credit_note.cgst or 0)
            - float(credit_note.sgst or 0)
            - float(credit_note.igst or 0)
        )

        narration = (
            f"Credit Note against Invoice "
            f"{invoice.invoice_no}"
        )

        party_entry_xml = f"""
        <LEDGERENTRIES.LIST>
            <LEDGERNAME>{self.esc(party_name)}</LEDGERNAME>
            <ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
            <ISPARTYLEDGER>Yes</ISPARTYLEDGER>
            <AMOUNT>{total}</AMOUNT>
        </LEDGERENTRIES.LIST>
        """

        sales_entry_xml = f"""
        <LEDGERENTRIES.LIST>
            <LEDGERNAME>{self.esc(sales_ledger_name)}</LEDGERNAME>
            <ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
            <ISPARTYLEDGER>No</ISPARTYLEDGER>
            <AMOUNT>-{sales_amount}</AMOUNT>
        </LEDGERENTRIES.LIST>
        """

        tax_xml = ""

        if cgst > 0:
            tax_xml += f"""
            <LEDGERENTRIES.LIST>
                <LEDGERNAME>{self.esc(self.cgst_ledger)}</LEDGERNAME>
                <ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
                <ISPARTYLEDGER>No</ISPARTYLEDGER>
                <AMOUNT>-{cgst}</AMOUNT>
            </LEDGERENTRIES.LIST>
            """

        if sgst > 0:
            tax_xml += f"""
            <LEDGERENTRIES.LIST>
                <LEDGERNAME>{self.esc(self.sgst_ledger)}</LEDGERNAME>
                <ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
                <ISPARTYLEDGER>No</ISPARTYLEDGER>
                <AMOUNT>-{sgst}</AMOUNT>
            </LEDGERENTRIES.LIST>
            """

        if igst > 0:
            tax_xml += f"""
            <LEDGERENTRIES.LIST>
                <LEDGERNAME>{self.esc(self.igst_ledger)}</LEDGERNAME>
                <ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
                <ISPARTYLEDGER>No</ISPARTYLEDGER>
                <AMOUNT>-{igst}</AMOUNT>
            </LEDGERENTRIES.LIST>
            """

        xml = f"""
    <ENVELOPE>
    <HEADER>
        <TALLYREQUEST>Import Data</TALLYREQUEST>
    </HEADER>

    <BODY>
        <IMPORTDATA>

        <REQUESTDESC>
            <REPORTNAME>Vouchers</REPORTNAME>

            <STATICVARIABLES>
            <SVCURRENTCOMPANY>{self.esc(tally_company_name)}</SVCURRENTCOMPANY>
            </STATICVARIABLES>

        </REQUESTDESC>

        <REQUESTDATA>

            <TALLYMESSAGE xmlns:UDF="TallyUDF">

            <VOUCHER ACTION="Create" VCHTYPE="Credit Note">

                <DATE>{credit_note_date}</DATE>

                <VOUCHERTYPENAME>
                Credit Note
                </VOUCHERTYPENAME>

                <VOUCHERNUMBER>
                {self.esc(voucher_no)}
                </VOUCHERNUMBER>

                <REFERENCE>
                {self.esc(invoice.invoice_no)}
                </REFERENCE>

                <PARTYLEDGERNAME>
                {self.esc(party_name)}
                </PARTYLEDGERNAME>

                <PARTYNAME>
                {self.esc(party_name)}
                </PARTYNAME>

                <BASICBASEPARTYNAME>
                {self.esc(party_name)}
                </BASICBASEPARTYNAME>

                <PERSISTEDVIEW>
                Accounting Voucher View
                </PERSISTEDVIEW>

                <ISINVOICE>No</ISINVOICE>

                <NARRATION>
                {self.esc(narration)}
                </NARRATION>

                {party_entry_xml}

                {sales_entry_xml}

                {tax_xml}

            </VOUCHER>

            </TALLYMESSAGE>

        </REQUESTDATA>

        </IMPORTDATA>
    </BODY>

    </ENVELOPE>
    """

        return xml.strip()

    def resolve_vendor_invoice_branch(self, invoice):
        """Resolve the Crystal Hues branch from the customer invoices linked to the vendor invoice.

        Vendor invoices are created branch-wise, so all linked customer invoices
        must point to exactly one CompanyBranch. This deliberately does not use
        the vendor master for branch selection.
        """
        branches = []
        seen = set()
        for item in list(getattr(invoice, "items", []) or []):
            customer_invoice = getattr(item, "customer_invoice", None)
            branch = getattr(customer_invoice, "company_branch", None) if customer_invoice else None
            branch_id = getattr(branch, "id", None)
            if branch is not None and branch_id not in seen:
                seen.add(branch_id)
                branches.append(branch)

        if len(branches) == 1:
            return branches[0]

        if len(branches) > 1:
            names = ", ".join((getattr(b, "branch_name", None) or str(b.id)) for b in branches)
            raise Exception(
                f"Vendor invoice spans multiple Crystal Hues branches ({names}). "
                "Please split it branch-wise before Tally sync."
            )

        raise Exception(
            "Unable to resolve the Crystal Hues invoice branch for this vendor invoice. "
            "At least one linked customer invoice with a Company Branch is required."
        )

    def get_vendor_expense_ledger(self, invoice):
        currency = (getattr(invoice, "currency", None) or "INR").strip().upper()
        if currency != "INR":
            return self.vendor_expense_international
        if bool(getattr(invoice, "gst_registered", False)):
            return self.vendor_expense_domestic_registered
        return self.vendor_expense_domestic_unregistered

    def get_vendor_party_ledger_name(self, invoice):
        vendor = getattr(invoice, "vendor", None)
        if vendor is None:
            raise Exception("Vendor missing in vendor invoice.")
        ledger = str(getattr(vendor, "tally_ledger_name", None) or "").strip()
        if not ledger:
            trans_id = getattr(vendor, "external_translator_id", None) or "-"
            raise Exception(
                f"Tally ledger is not mapped for vendor {trans_id} - {getattr(vendor, 'name', '')}. "
                "Please complete Vendor Tally Mapping first."
            )
        return ledger

    def vendor_jobcard_reference(self, invoice):
        jobcards = []
        for item in list(getattr(invoice, "items", []) or []):
            code = str(getattr(item, "jobcard_code", None) or "").strip()
            if code and code not in jobcards:
                jobcards.append(code)
        return ", ".join(jobcards) or "-"

    def build_vendor_journal_xml(self, invoice):
        """Build the vendor bill booking entry exactly as the current manual Journal process.

        Domestic GST registered:
            Dr Translation Expenses (Domestic)_GST_Registered_ITC  taxable
            Dr Input Receivable IGST @ 18%                         GST
            Cr TDS on Professional                                 TDS
            Cr Vendor ledger                                       net payable

        Domestic GST unregistered:
            Dr Translation Expenses (Domestic)_GST_Unregistered    taxable
            Cr TDS on Professional                                 TDS
            Cr Vendor ledger                                       net payable

        International:
            Dr Translation Expenses (International)                INR equivalent
            Cr Vendor ledger                                       INR equivalent
        """
        vendor = getattr(invoice, "vendor", None)
        if vendor is None:
            raise Exception("Vendor missing in vendor invoice.")

        company_branch = self.resolve_vendor_invoice_branch(invoice)
        tally_company_name = self.resolve_tally_company_name(company_branch)
        party_name = self.get_vendor_party_ledger_name(invoice)
        expense_ledger = self.get_vendor_expense_ledger(invoice)

        invoice_date_obj = getattr(invoice, "invoice_date", None)
        if invoice_date_obj is None:
            raise Exception("Vendor invoice date is missing.")
        invoice_date = invoice_date_obj.strftime("%Y%m%d")

        currency_code = self.normalize_currency_code(
            getattr(invoice, "currency", None) or "INR"
        )
        rate_to_inr = self.get_rate_to_inr(currency_code, invoice_date_obj)

        foreign_taxable = self.money(getattr(invoice, "calculated_taxable_amount", 0))
        foreign_gst = self.money(getattr(invoice, "calculated_gst_amount", 0))
        foreign_tds = self.money(getattr(invoice, "calculated_tds_amount", 0))
        foreign_net = self.money(getattr(invoice, "calculated_net_payable_amount", 0))

        if currency_code == "INR":
            taxable = foreign_taxable
            gst = foreign_gst
            tds = foreign_tds
            net_payable = foreign_net
        else:
            taxable = self.money(foreign_taxable * rate_to_inr)
            gst = 0.0
            tds = 0.0
            net_payable = taxable

        if taxable <= 0:
            raise Exception("Vendor invoice taxable amount must be greater than zero for Tally sync.")

        jobcards = self.vendor_jobcard_reference(invoice)
        narration = (
            f"{currency_code} {foreign_taxable:.4f} @ {float(rate_to_inr):.2f} "
            f"against JobCard No. {jobcards}"
        )
        vendor_invoice_no = str(getattr(invoice, "vendor_invoice_no", None) or invoice.id)

        entries = []

        # Debit expense.
        entries.append(f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc_exact(expense_ledger)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>No</ISPARTYLEDGER>
    <AMOUNT>-{taxable:.2f}</AMOUNT>
</LEDGERENTRIES.LIST>
""")

        # GST-registered domestic vendor invoices follow the supplied manual
        # sample and book the full 18% input tax to the IGST input ledger.
        if currency_code == "INR" and bool(getattr(invoice, "gst_registered", False)) and gst > 0:
            entries.append(f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc_exact(self.vendor_input_igst_ledger)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>Yes</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>No</ISPARTYLEDGER>
    <AMOUNT>-{gst:.2f}</AMOUNT>
</LEDGERENTRIES.LIST>
""")

        if currency_code == "INR" and tds > 0:
            entries.append(f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc_exact(self.vendor_tds_ledger)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>No</ISPARTYLEDGER>
    <AMOUNT>{tds:.2f}</AMOUNT>
</LEDGERENTRIES.LIST>
""")

        entries.append(f"""
<LEDGERENTRIES.LIST>
    <LEDGERNAME>{self.esc_exact(party_name)}</LEDGERNAME>
    <ISDEEMEDPOSITIVE>No</ISDEEMEDPOSITIVE>
    <ISPARTYLEDGER>Yes</ISPARTYLEDGER>
    <AMOUNT>{net_payable:.2f}</AMOUNT>
    <BILLALLOCATIONS.LIST>
        <NAME>{self.esc(vendor_invoice_no)}</NAME>
        <BILLTYPE>New Ref</BILLTYPE>
        <AMOUNT>{net_payable:.2f}</AMOUNT>
    </BILLALLOCATIONS.LIST>
</LEDGERENTRIES.LIST>
""")

        debit_total = self.money(taxable + gst)
        credit_total = self.money(tds + net_payable)
        if abs(debit_total - credit_total) > 0.02:
            raise Exception(
                f"Vendor Tally journal is not balanced: debit {debit_total:.2f}, "
                f"credit {credit_total:.2f}."
            )

        ledger_entries = "\n".join(entries)
        voucher_type = self.vendor_voucher_type or "Journal"

        # VOUCHERNUMBER is intentionally omitted. The user's Journal voucher
        # type already auto-generates numbers such as CH/VN/BN/2026/8/18.
        # Vendor invoice number is retained as Reference/New Ref for traceability.
        xml = f"""
<ENVELOPE>
  <HEADER>
    <TALLYREQUEST>Import Data</TALLYREQUEST>
  </HEADER>
  <BODY>
    <IMPORTDATA>
      <REQUESTDESC>
        <REPORTNAME>Vouchers</REPORTNAME>
        <STATICVARIABLES>
          <SVCURRENTCOMPANY>{self.esc(tally_company_name)}</SVCURRENTCOMPANY>
        </STATICVARIABLES>
      </REQUESTDESC>
      <REQUESTDATA>
        <TALLYMESSAGE xmlns:UDF="TallyUDF">
          <VOUCHER ACTION="Create" VCHTYPE="{self.esc(voucher_type)}">
            <DATE>{invoice_date}</DATE>
            <VOUCHERTYPENAME>{self.esc(voucher_type)}</VOUCHERTYPENAME>
            <REFERENCE>{self.esc(vendor_invoice_no)}</REFERENCE>
            <PARTYLEDGERNAME>{self.esc_exact(party_name)}</PARTYLEDGERNAME>
            <PARTYNAME>{self.esc_exact(party_name)}</PARTYNAME>
            <BASICBASEPARTYNAME>{self.esc_exact(party_name)}</BASICBASEPARTYNAME>
            <PERSISTEDVIEW>Accounting Voucher View</PERSISTEDVIEW>
            <ISINVOICE>No</ISINVOICE>
            <NARRATION>{self.esc(narration)}</NARRATION>
            {ledger_entries}
          </VOUCHER>
        </TALLYMESSAGE>
      </REQUESTDATA>
    </IMPORTDATA>
  </BODY>
</ENVELOPE>
"""
        return xml.strip()

    def push_vendor_invoice(self, invoice):
        if getattr(invoice, "tally_sync_status", None) == "Synced":
            raise Exception("Vendor invoice is already synced to Tally.")

        xml = self.build_vendor_journal_xml(invoice)
        try:
            response = self.post_to_tally(xml)
            response_text = response.text or ""

            if response.status_code != 200:
                raise Exception(f"Tally HTTP error {response.status_code}: {response_text}")

            upper_response = response_text.upper()
            if "<LINEERROR>" in upper_response:
                raise Exception(response_text)
            if "<CREATED>0</CREATED>" in upper_response and "<ALTERED>0</ALTERED>" in upper_response:
                raise Exception(f"Tally did not create vendor journal: {response_text}")

            invoice.tally_sync_status = "Synced"
            invoice.tally_sync_at = datetime.utcnow()
            invoice.tally_sync_error = None
            # Journal numbering remains controlled by Tally. The external/vendor
            # invoice number is stored as Reference/New Ref rather than forcing a
            # voucher number that could break the existing Tally numbering series.
            invoice.tally_voucher_no = None
            db.session.commit()
            return response_text

        except Exception as exc:
            invoice.tally_sync_status = "Failed"
            invoice.tally_sync_error = str(exc)
            db.session.commit()
            raise

    def push_invoice(self, invoice):
        xml = self.build_sales_voucher_xml(invoice)

        try:
            response = self.post_to_tally(xml)

            response_text = response.text or ""

            if response.status_code != 200:
                raise Exception(f"Tally HTTP error {response.status_code}: {response_text}")

            upper_response = response_text.upper()

            if "<LINEERROR>" in upper_response:
                raise Exception(response_text)

            if "<CREATED>0</CREATED>" in upper_response and "<ALTERED>0</ALTERED>" in upper_response:
                raise Exception(f"Tally did not create voucher: {response_text}")

            invoice.tally_sync_status = "Synced"
            invoice.tally_sync_at = datetime.utcnow()
            invoice.tally_sync_error = None
            invoice.tally_voucher_no = invoice.invoice_no

            db.session.commit()

            return response_text

        except Exception as e:
            invoice.tally_sync_status = "Failed"
            invoice.tally_sync_error = str(e)
            db.session.commit()
            raise

    def push_credit_note(self, credit_note):

        xml = self.build_credit_note_xml(credit_note)

        try:

            response = self.post_to_tally(xml)

            response_text = response.text or ""

            if response.status_code != 200:
                raise Exception(
                    f"Tally HTTP error {response.status_code}: {response_text}"
                )

            upper_response = response_text.upper()

            if "<LINEERROR>" in upper_response:
                raise Exception(response_text)

            if "<CREATED>0</CREATED>" in upper_response and "<ALTERED>0</ALTERED>" in upper_response:
                raise Exception(
                    f"Tally did not create voucher: {response_text}"
                )

            credit_note.tally_sync_status = "Synced"
            credit_note.tally_sync_at = datetime.utcnow()
            credit_note.tally_sync_error = None
            credit_note.tally_voucher_no = credit_note.credit_note_no

            db.session.commit()

            return response_text

        except Exception as e:

            credit_note.tally_sync_status = "Failed"
            credit_note.tally_sync_error = str(e)

            db.session.commit()

            raise
        