from pathlib import Path
from saxonche import PySaxonProcessor
import xml.etree.ElementTree as ET

def xml_check_schematron(xml_path: str , xslt_path: str = "xslt/EN16931-CII-validation.xslt"):
    """
    Applies Schematron validation on an XML file and returns the errors.
    :param xml_path: Path to the XML file to validate.
    :param xslt_path: Path to the XSLT file containing the validation rules.
    :return: Validation report containing the errors.
    """

    NS = {"svrl": "http://purl.oclc.org/dsdl/svrl"}
    base = Path(__file__).parent.resolve()
    xslt_path = (base / xslt_path).as_posix()

    with PySaxonProcessor(license=False) as proc:
        xslt = proc.new_xslt30_processor()
        #xslt.set_cwd(base.as_posix())
        result = xslt.transform_to_string(
            source_file=xml_path,
            stylesheet_file=xslt_path
        )

    # Parse the result (SVRL XML string)
    root = ET.fromstring(result)
    fails = root.findall(".//svrl:failed-assert", NS)

    return {f"{len(fails)} fails": create_report(fails, NS)}

def create_report(fails:list, NS):
    """
    Displays errors from schematron validation
    :param fails: Validation report containing the errors.
    :return: None
    """
    list = []

    for fa in fails:
        rid = fa.get("id")
        loc = fa.get("location")
        msg = fa.findtext("svrl:text", default="", namespaces=NS)
        fail = {rid : msg, "Location": loc}
        list.append(fail)
    return list



