"""
builder/xml_generator.py — Convert structured accounting entries into the exact
TallyPrime import XML envelope that TallyPrime expects on Port 9000.
"""
import xml.etree.ElementTree as ET

from config import COMPANY_NAME  # noqa: F401  (kept for parity / future use)


def build_voucher_xml(entries: list) -> str:
    """
    entries: output from claude_processor.classify_transactions()
    returns: XML string ready to POST to Tally
    """
    envelope = ET.Element("ENVELOPE")

    # ── Header ──────────────────────────────
    header = ET.SubElement(envelope, "HEADER")
    ET.SubElement(header, "TALLYREQUEST").text = "Import Data"

    # ── Body ────────────────────────────────
    body = ET.SubElement(envelope, "BODY")
    imp  = ET.SubElement(body, "IMPORTDATA")
    req  = ET.SubElement(imp, "REQUESTDESC")
    ET.SubElement(req, "REPORTNAME").text = "Vouchers"
    ET.SubElement(req, "STATICVARIABLES")  # placeholder

    req_data = ET.SubElement(imp, "REQUESTDATA")

    for entry in entries:
        msg = ET.SubElement(req_data, "TALLYMESSAGE", xmlns="UDF:TallyUDF")
        voucher = ET.SubElement(
            msg, "VOUCHER",
            VCHTYPE=entry["voucher_type"], ACTION="Create",
        )

        # Core fields
        ET.SubElement(voucher, "DATE").text            = str(entry["date"])
        ET.SubElement(voucher, "VOUCHERTYPENAME").text = entry["voucher_type"]
        ET.SubElement(voucher, "NARRATION").text       = entry.get("narration", "")
        ET.SubElement(voucher, "REFERENCE").text       = entry.get("reference", "")

        # Debit leg (Tally: deemed-positive = Yes, amount negative)
        dr = ET.SubElement(voucher, "ALLLEDGERENTRIES.LIST")
        ET.SubElement(dr, "LEDGERNAME").text       = entry["debit_ledger"]
        ET.SubElement(dr, "ISDEEMEDPOSITIVE").text = "Yes"
        ET.SubElement(dr, "AMOUNT").text           = str(-abs(float(entry["amount"])))

        # Credit leg
        cr = ET.SubElement(voucher, "ALLLEDGERENTRIES.LIST")
        ET.SubElement(cr, "LEDGERNAME").text       = entry["credit_ledger"]
        ET.SubElement(cr, "ISDEEMEDPOSITIVE").text = "No"
        ET.SubElement(cr, "AMOUNT").text           = str(abs(float(entry["amount"])))

        # VAT leg (if applicable)
        if float(entry.get("vat_amount", 0) or 0) > 0:
            vat = ET.SubElement(voucher, "ALLLEDGERENTRIES.LIST")
            ET.SubElement(vat, "LEDGERNAME").text       = "Input VAT"
            ET.SubElement(vat, "ISDEEMEDPOSITIVE").text = "Yes"
            ET.SubElement(vat, "AMOUNT").text           = str(-abs(float(entry["vat_amount"])))

    xml_str = ET.tostring(envelope, encoding="unicode")
    return '<?xml version="1.0" encoding="utf-8"?>\n' + xml_str
