import json

from demos.grownet_trace_main import run_for_test


def test_text_benchmark_emits_start_result_and_summary():
    output = run_for_test(
        [
            "--lang",
            "python",
            "--benchmark",
            "--scenario",
            "single_neuron",
            "--benchmark-warmup",
            "1",
            "--benchmark-iterations",
            "2",
            "--benchmark-repeat",
            "2",
        ]
    )
    assert "[benchmark.start]" in output
    assert "[benchmark.result]" in output
    assert "[benchmark.summary]" in output
    assert "min_us=" in output
    assert "p50_us=" in output
    assert "p95_us=" in output
    assert "p99_us=" in output
    assert "max_us=" in output
    assert "mean_us=" in output
    assert "total_elapsed_ms=" in output
    assert "throughput_per_sec=" in output


def test_jsonl_benchmark_output_parses_and_has_required_fields():
    output = run_for_test(
        [
            "--lang",
            "python",
            "--benchmark",
            "--benchmark-format",
            "jsonl",
            "--scenario",
            "two_layer",
            "--benchmark-warmup",
            "1",
            "--benchmark-iterations",
            "2",
            "--benchmark-repeat",
            "1",
        ]
    )
    payloads = [json.loads(line) for line in output.splitlines() if line.strip()]
    assert len(payloads) == 3

    start_payload = payloads[0]
    result_payload = payloads[1]
    summary_payload = payloads[2]

    assert start_payload["event"] == "benchmark.start"
    assert start_payload["warmup"] == 1
    assert start_payload["iterations"] == 2
    assert start_payload["repeat"] == 1

    assert result_payload["event"] == "benchmark.result"
    assert result_payload["count"] == 2
    assert "min_us" in result_payload
    assert "p50_us" in result_payload
    assert "p95_us" in result_payload
    assert "p99_us" in result_payload
    assert "max_us" in result_payload
    assert "mean_us" in result_payload
    assert "total_elapsed_ms" in result_payload
    assert "throughput_per_sec" in result_payload

    assert summary_payload["event"] == "benchmark.summary"
    assert "overall_mean_us" in summary_payload
    assert "best_p50_us" in summary_payload
    assert "best_p99_us" in summary_payload
    assert "best_throughput_per_sec" in summary_payload
