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


def prettify_xml(element):
    rough_string = ET.tostring(element, encoding="utf-8")
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")


def load_unreal_report(json_path):
    with open(json_path, "r", encoding="utf-8-sig") as f:
        return json.load(f)


def create_junit_xml(report_data):
    tests = report_data.get("tests", [])

    total_tests = len(tests)
    total_failures = 0
    total_time = 0.0

    testsuites = ET.Element(
        "testsuites",
        tests=str(total_tests),
        failures="0",
        errors="0",
    )

    testsuite = ET.SubElement(
        testsuites,
        "testsuite",
        name="UnrealAutomation",
        tests=str(total_tests),
        failures="0",
        errors="0",
    )

    for test in tests:
        test_name = test.get("testDisplayName", "UnknownTest")
        full_test_path = test.get("fullTestPath", test_name)
        state = test.get("state", "Unknown")
        duration = float(test.get("duration", 0.0))

        total_time += duration

        testcase = ET.SubElement(
            testsuite,
            "testcase",
            classname="UnrealAutomation",
            name=full_test_path,
            time=f"{duration:.3f}",
        )

        if state.lower() != "success":
            total_failures += 1

            failure_message = []

            entries = test.get("entries", [])
            for entry in entries:
                event_message = entry.get("event", {}).get("message", "")
                if event_message:
                    failure_message.append(event_message)

            failure_text = "\n".join(failure_message)

            failure = ET.SubElement(
                testcase,
                "failure",
                message="Automation test failed",
                type="AssertionError",
            )

            failure.text = failure_text

    testsuite.set("failures", str(total_failures))
    testsuite.set("time", f"{total_time:.3f}")

    testsuites.set("failures", str(total_failures))

    return testsuites


def main():
    if len(sys.argv) != 3:
        print("Usage:")
        print("python unreal_json_to_junit.py input.json output.xml")
        sys.exit(1)

    input_json = Path(sys.argv[1])
    output_xml = Path(sys.argv[2])

    report_data = load_unreal_report(input_json)

    junit_xml = create_junit_xml(report_data)

    xml_string = prettify_xml(junit_xml)

    with open(output_xml, "w", encoding="utf-8") as f:
        f.write(xml_string)

    print(f"JUnit XML written to: {output_xml}")


if __name__ == "__main__":
    main()
