import json
import logging
from datetime import datetime
from pathlib import Path

from junit_xml import TestCase, TestSuite

from test_automation_suite.core.context import Context
from test_automation_suite.core.task_dispatcher import TaskDispatcher
from test_automation_suite.templates import render_and_write_template

logger = logging.getLogger(__name__)


def dump_test_results(context: Context, task_dispatcher: TaskDispatcher, results_json: str) -> None:
    json_path = context.output_directory / "results.json"
    junit_path = context.output_directory / "results.xml"
    html_path = context.output_directory / "results.html"

    with json_path.open("w+") as json_file:
        json_file.write(results_json)

    # TODO: This should be called with results_json instead of the task_dispatcher
    dump_junit_results(context, task_dispatcher, junit_path)
    dump_html_results(results_json, html_path)


def dump_junit_results(
    context: Context,
    task_dispatcher: TaskDispatcher,
    output_filename: Path,
) -> None:
    test_cases: list[TestCase] = []
    for label, result in task_dispatcher.results().items():
        test_case = TestCase(
            name=label,
            status="Success" if result.success else "Failure",
            log="\n".join(result.log),
            allow_multiple_subelements=True,
        )
        test_cases.append(test_case)
        # definition for the stuff in here https://github.com/kyrus/python-junit-xml/blob/master/junit_xml/__init__.py
    ts = TestSuite(
        name=task_dispatcher._state.task_name,
        test_cases=test_cases,
        timestamp=task_dispatcher._state.started_at.strftime("%Y-%m-%d_%H-%M-%S"),
        log=context.config.output_base_directory,
    )
    with output_filename.open("w") as f:
        TestSuite.to_file(f, [ts], prettyprint=False)


def dump_html_results(results_json: str, output: Path) -> None:
    results = json.loads(results_json)
    formatted_date = datetime.strptime(results["Test date"], "%Y-%m-%d_%H-%M-%S").strftime(
        "Test from %Y/%m/%d at %H:%M:%S"
    )
    total_tests = len(results["Test results"])
    passed_tests = sum(1 for result in results["Test results"].values() if result["success"])

    _ = render_and_write_template(
        "test_report.html",
        output,
        {
            "results": results,
            "formatted_date": formatted_date,
            "total_tests": total_tests,
            "passed_tests": passed_tests,
        },
    )
