#!/usr/bin/python3

import json
import logging
import os
import runpy
import sys
import tempfile
from pathlib import Path

os.environ["MPLBACKEND"] = "Agg"
logging.getLogger("matplotlib.font_manager").setLevel(logging.ERROR)

import matplotlib.pyplot as plt
import numpy as np


def test_plot(mode, data_path, expected_axes):
    captured = []

    def capture_plot():
        figure = plt.gcf()
        assert len(figure.axes) == expected_axes
        if mode == "hist":
            assert figure.axes[0].patches, "No histogram bars were plotted"
        else:
            assert all(ax.lines for ax in figure.axes), "No sample data was plotted"

        with tempfile.TemporaryFile() as image:
            figure.savefig(image, format="png")
            assert image.tell() > 1000, "Empty or invalid plot image"
        captured.append(True)

    previous_argv, previous_show = sys.argv, plt.show
    try:
        sys.argv = ["jitterplot", mode, str(data_path)]
        plt.show = capture_plot
        runpy.run_path("/usr/bin/jitterplot", run_name="__main__")
    finally:
        sys.argv, plt.show = previous_argv, previous_show
        plt.close("all")

    assert captured, f"jitterplot {mode} did not display a plot"


with tempfile.TemporaryDirectory() as directory:
    directory = Path(directory)

    histogram = directory / "results.json"
    histogram.write_text(
        json.dumps({
            "cpu": {
                "0": {
                    "histogram": {"10": 2, "20": 3},
                    "min": 10,
                    "avg": 15,
                    "max": 20,
                }
            }
        }),
        encoding="utf-8",
    )
    test_plot("hist", histogram, expected_axes=1)

    samples = directory / "samples.raw"
    sample_dtype = np.dtype([
        ("CPUID", "u4"),
        ("Seconds", "u8"),
        ("Nanoseconds", "u8"),
        ("Value", "u8"),
    ])
    np.array([
        (0, 1, 0, 15),
        (0, 2, 0, 20),
        (1, 1, 0, 25),
        (1, 2, 0, 30),
    ], dtype=sample_dtype).tofile(samples)
    test_plot("samples", samples, expected_axes=2)

print("jitterplot autopkgtests passed")
