from typing import List

from lxml.etree import fromstring as xml_bytes_parser

from maps_adv.export.lib.core.url_signer import ActionUrlSigner
from maps_adv.common.helpers.timing import TimeDiff, async_time_diff

from .transform.base import pipeline_data_transform
from .tree.root import Root


@async_time_diff
async def prepare_xml_file(
    data: dict,
    validators: List,
    filename: str,
    navi_signer: ActionUrlSigner,
    ctype: str,
) -> dict:
    with TimeDiff("prepare_xml_file.make_xml_str"):
        xml_data_dict, attrs = await pipeline_data_transform(data, navi_signer, ctype)
        xml_data = str(Root.from_dict(xml_data_dict))

    with TimeDiff("prepare_xml_file.parse_xml_to_tree"):
        xml = xml_bytes_parser(xml_data.encode())

    with TimeDiff("prepare_xml_file.validators"):
        for validate in validators:
            validate(xml)

    with TimeDiff("prepare_xml_file.save_to_file"):
        with open(filename, "w") as out:
            out.write(xml_data)

    return attrs
