"""
push/tally_importer.py — POST the XML envelope to TallyPrime on Port 9000.
TallyPrime must be running with ODBC / gateway enabled.
"""
import requests
import xml.etree.ElementTree as ET

from config import TALLY_URL


def push_to_tally(xml_string: str) -> dict:
    """
    Returns: {"success": bool, "message": str, "imported": int}
    """
    try:
        response = requests.post(
            TALLY_URL,
            data=xml_string.encode("utf-8"),
            headers={"Content-Type": "text/xml; charset=utf-8"},
            timeout=60,
        )
        response.raise_for_status()

        root    = ET.fromstring(response.text)
        created = root.findtext(".//CREATED", "0")
        altered = root.findtext(".//ALTERED", "0")
        errors  = root.findtext(".//ERRORS", "0")

        if int(errors or 0) > 0:
            err_msg = root.findtext(".//LINEERROR", None) or root.findtext(".//ERRORMSG", "Unknown error")
            return {"success": False, "message": err_msg, "imported": 0}

        return {
            "success": True,
            "message": f"{created} created, {altered} altered",
            "imported": int(created or 0),
        }

    except requests.exceptions.ConnectionError:
        return {
            "success": False,
            "message": "Cannot connect. Is TallyPrime running with the gateway on Port 9000?",
            "imported": 0,
        }
    except Exception as e:  # noqa: BLE001
        return {"success": False, "message": str(e), "imported": 0}


def enable_tally_gateway():
    """Reminder: how to enable the XML/ODBC gateway in TallyPrime."""
    print("""
    In TallyPrime:
    1. Press F1 > Settings > Connectivity  (or F12 > Advanced Config)
    2. Set "TallyPrime acts as" -> Both
    3. Port: 9000
    4. Enable: Allow Server to use ODBC
    5. Accept and restart Tally
    6. Test: open http://localhost:9000 in your browser
    """)
