from __future__ import annotations

from pathlib import Path

from testing.ci.summary import RunSummary, load_junit_cases, load_junit_summary, render_payload


def test_load_junit_summary_combines_suites(tmp_path: Path) -> None:
    junit = tmp_path / "results.xml"
    junit.write_text(
        '<testsuites><testsuite tests="3" failures="1" errors="0" skipped="1"/></testsuites>'
    )

    summary = load_junit_summary([junit])

    assert summary == RunSummary(tests=3, failures=1, errors=0, skipped=1)
    payload = render_payload(suite="bstein_home", ok=2, failed=0, summary=summary)
    assert 'platform_quality_gate_runs_total{suite="bstein_home",status="ok"} 2' in payload
    assert 'bstein_home_quality_gate_tests_total{suite="bstein_home",result="skipped"} 1' in payload
    assert 'platform_quality_gate_workspace_line_coverage_percent{suite="bstein_home"} 0.000' in payload
    assert 'platform_quality_gate_source_lines_over_500_total{suite="bstein_home"} 0' in payload


def test_load_junit_cases_and_render_test_case_metrics(tmp_path: Path) -> None:
    junit = tmp_path / "cases.xml"
    junit.write_text(
        (
            "<testsuite>"
            '<testcase classname="app.health" name="test_ok" />'
            '<testcase classname="app.health" name="test_fail"><failure/></testcase>'
            "</testsuite>"
        ),
        encoding="utf-8",
    )

    cases = load_junit_cases([junit])
    assert ("app.health::test_ok", "passed") in cases
    assert ("app.health::test_fail", "failed") in cases

    payload = render_payload(
        suite="bstein_home",
        ok=1,
        failed=0,
        summary=RunSummary(tests=2, failures=1, errors=0, skipped=0),
        test_cases=cases,
    )
    assert 'platform_quality_gate_test_case_result{suite="bstein_home",test="app.health::test_fail",status="failed"} 1' in payload
