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

from gchr.gchr_model import GchrExportConfig

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


def export_honda_csv(export_cfg: GchrExportConfig):
    dealer_number = "HDE10020"
    fiscal_year = export_cfg.current_year
    ts = datetime.now().strftime("%m%d%Y;%H%M%S")
    header = "\n".join(
        f"{dealer_number};Dealernumber",
        ";Honda Germany",
        f"{export_cfg.current_year};Evaluation;{export_cfg.current_month}"
        f"{fiscal_year};Fiscal-Year;{export_cfg.first_month}"
        f";Timestamp;{ts}",
    )

    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())