import os
import xml.etree.ElementTree as ET
from typing import Any


def _map_test_report(testcase: ET.Element) -> dict[str, Any]:
    failure = testcase.find("failure")
    return {
        "name": testcase.attrib.get("name"),
        "outcome": "failed" if failure is not None else "passed",
        "message": failure.attrib.get("message") if failure is not None else None,
        "longrepr": failure.text.strip() if failure is not None and failure.text else None,
    }


def parse(xml_path: str, return_code: int) -> dict[str, Any] | None:
    if os.path.getsize(xml_path) == 0:
        return None

    tree = ET.parse(xml_path)
    root = tree.getroot()

    for testsuite in root.findall("testsuite"):
        tests = int(testsuite.attrib.get("tests", 0))
        failures = int(testsuite.attrib.get("failures", 0))
        errors = int(testsuite.attrib.get("errors", 0))

        summary = {
            "collected": tests,
            "failed": failures,
            "error": errors,
            "passed": tests - failures - errors,
            "total": tests,
        }

        test_results = list(map(_map_test_report, testsuite.findall("testcase")))

        return {
            "exitCode": return_code,
            "summary": summary,
            "tests": test_results,
        }

    return None
