"""Tests for Sondeo report rendering and CLI report command."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from sondeo import report
from sondeo.cli import main
from sondeo.profiler.logging import clear_events
from sondeo.profiler.memory import clear_results as clear_memory_results
from sondeo.profiler.timer import clear_results as clear_timer_results
from sondeo.profiler.timer import profile
from sondeo.profiler.trace import clear_results as clear_trace_results
from sondeo.profiler.trace import trace


def _clear_all() -> None:
    clear_events()
    clear_timer_results()
    clear_memory_results()
    clear_trace_results()


def test_report_markdown_includes_summary_and_call_tree() -> None:
    _clear_all()

    @profile
    def compute() -> int:
        return sum(range(30_000))

    with trace(filter_stdlib=False):
        compute()

    output = report(format="markdown", clear=False, show_timeline=False, print_output=False)

    assert isinstance(output, str)
    assert "# Sondeo Profiling Report" in output
    assert "## Summary" in output
    assert "## Call Tree" in output
    assert "### Trace 1" in output

    _clear_all()


def test_report_json_includes_summary_and_traces() -> None:
    _clear_all()

    with trace(filter_stdlib=False):
        _ = sum(range(15_000))

    data = report(format="json", clear=False, show_timeline=False, print_output=False)

    assert isinstance(data, dict)
    assert "summary" in data
    assert "traces" in data
    assert data["summary"]["deepest_call_stack"] >= 1
    assert len(data["traces"]) == 1

    _clear_all()


def test_cli_report_renders_markdown_from_saved_json(
    tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
    payload = {
        "summary": {
            "total_time_ms": 12.3,
            "peak_memory_mb": 4.5,
            "deepest_call_stack": 2,
            "slowest_function": {"name": "do_work", "elapsed_ms": 9.1, "calls": 1},
        },
        "timings": [{"name": "do_work", "elapsed_ms": 9.1, "calls": 1}],
        "memory": [],
        "traces": [],
        "timeline": [],
    }
    json_path = tmp_path / "report.json"
    json_path.write_text(json.dumps(payload), encoding="utf-8")

    main(["report", str(json_path), "--format", "markdown"])
    captured = capsys.readouterr()

    assert "# Sondeo Profiling Report" in captured.out
