import pytest
import numpy as np
import matplotlib

matplotlib.use('Agg')  # 使用非交互后端，避免显示
from privacy_tuner.visualization.plotter import Visualizer
import os
import tempfile


def test_plot_risk_utility_scatter():
    # 生成模拟结果
    results = []
    for i in range(50):
        results.append({
            'risk': np.random.rand(),
            'utility': np.random.rand(),
            'params': {'a': i}
        })
    best = {'risk': 0.2, 'utility': 0.9}

    viz = Visualizer()
    with tempfile.TemporaryDirectory() as tmpdir:
        save_path = os.path.join(tmpdir, 'test.png')
        fig = viz.plot_risk_utility_scatter(
            results,
            highlight_best=best,
            risk_constraint=(0.1, 0.8),
            save_path=save_path
        )
        assert os.path.exists(save_path)
        assert fig is not None
    viz.close_all()


def test_plot_parameter_sensitivity():
    results = []
    for i in range(50):
        results.append({
            'risk': np.random.rand(),
            'utility': np.random.rand(),
            'params': {'param_x': np.random.rand() * 10}
        })

    viz = Visualizer()
    with tempfile.TemporaryDirectory() as tmpdir:
        save_path = os.path.join(tmpdir, 'sensitivity.png')
        fig = viz.plot_parameter_sensitivity(
            results,
            param_name='param_x',
            save_path=save_path
        )
        assert os.path.exists(save_path)
        assert fig is not None
    viz.close_all()


def test_chinese_font_setup():
    # 测试初始化是否正常，不报错
    viz = Visualizer()
    assert viz is not None
    viz.close_all()