import csv
import xml.etree.ElementTree as ET
from pathlib import Path
from xml.dom import minidom

from gchr.gchr_model import GchrExportConfig

# <summary>
#  V = Volkswagen,
#  A = Audi,
#  S = Seat,
#  C = Skoda,
#  E = Bentley,
#  L = Lamborghini
#  </summary>
# internal enum Hauptmarke { V, A, S, C, E, L };

MODEL_CODE = {
    "01": "0600",
    "02": "0603",
}


def export_volkswagen_xml(export_cfg: GchrExportConfig):
    header = {
        "tns:PartnerKey": {
            "tns:Country": "DEU",
            "tns:Brand": "V",
            "tns:PartnerNumber": "21996",
        },
        "tns:IsCumulative": "true",
        "tns:AccountingDate": {
            "tns:AccountingMonth": export_cfg.current_month,
            "tns:AccountingYear": export_cfg.current_year,
        },
        "tns:Currency": "EUR",
        "tns:Level": "1",
    }

    records = []
    for row in sorted(export_cfg.bookkeep_records, key=lambda x: x["Account"] + x["CostAccountingString"]):
        val = "{0:.2f}".format(row["CumulatedYear"] * -1)
        if val[0] != "-":
            val = "+" + val
        records.append(
            {
                "tns:ProfitCenter": "00",
                "tns:AccountKey": account_number(row),
                "tns:AccountValue": val,
            }
        )

    base_dir = Path(export_cfg.export_file).parent.parent.parent
    add_values = f"{base_dir}\\data\\Manuelle_Eingabe_{export_cfg.current_year}-{export_cfg.current_month}.csv"
    if Path(add_values).exists():
        with open(add_values, "r", encoding="latin-1") as frh:
            csv_frh = csv.DictReader(frh, delimiter=";")
            for row in csv_frh:
                records.append(
                    {
                        "tns:ProfitCenter": "00",
                        "tns:AccountKey": row["Kontonummer"][1:],
                        "tns:AccountValue": "+{0:.2f}".format(float(row["Akt.Monat"].replace(",", "."))),
                    }
                )

    nsmap = {"xmlns:tns": "http://xmldefs.volkswagenag.com/Retail/AccountBalanceDTS/V1"}
    root = ET.Element("tns:ShowAccountBalance", nsmap)
    root = dict_to_xml(root, header)

    record_list = ET.SubElement(root, "tns:Accounts")
    for r in records:
        dict_to_xml(ET.SubElement(record_list, "tns:Account"), r)

    raw_xml = ET.tostring(root, encoding="latin-1")
    with open(export_cfg.export_file, "w", encoding="latin-1") as fwh:
        fwh.write(minidom.parseString(raw_xml).toprettyxml(indent="  "))


def dict_to_xml(root: ET.Element, subtree: dict):
    if isinstance(subtree, list):
        for item in subtree:
            dict_to_xml(root, item)
        return root

    for key, value in subtree.items():
        e = ET.SubElement(root, key)
        if isinstance(value, dict):
            dict_to_xml(e, value)
        else:
            e.text = str(value)
    return root


def account_number(row: dict[str, str]) -> str:
    res = {
        "Brand": row["Make"],
        "ModelCode": MODEL_CODE.get(row["Make"], "0000"),
        "Account": row["Account"],
        "CostCentre": row["Origin"],
        "TradeChannel": row["SalesChannel"],
        "CostUnit": row["CostCarrier"],
        "Location": row["Site"],
        "TaxCode": "000",
    }
    return "".join(res.values())