# paint/histogram.py
import matplotlib.pyplot as plt
import numpy as np


def histogram(data=None, bins=10, title="Histogram",
              xlabel="Value", ylabel="Frequency",
              color='skyblue', edgecolor='black',
              density=False, cumulative=False,
              show_mean=False, show_median=False):
    """
    绘制直方图

    参数:
    data: 数据数组
    bins: 柱子数量或边界
    title: 图表标题
    xlabel: X轴标签
    ylabel: Y轴标签
    color: 柱子颜色
    edgecolor: 边框颜色
    density: 是否显示密度
    cumulative: 是否累积
    show_mean: 是否显示均值线
    show_median: 是否显示中位数线
    """
    fig, ax = plt.subplots(figsize=(10, 6))

    # 生成默认数据
    if data is None:
        np.random.seed(42)
        data = np.random.normal(0, 1, 1000)

    # 绘制直方图
    n, bins, patches = ax.hist(data, bins=bins,
                               color=color, edgecolor=edgecolor,
                               alpha=0.7, density=density,
                               cumulative=cumulative)

    # 计算统计量
    mean_val = np.mean(data)
    median_val = np.median(data)
    std_val = np.std(data)

    # 添加统计线
    if show_mean:
        ax.axvline(mean_val, color='red', linestyle='--',
                   linewidth=2, label=f'Mean: {mean_val:.2f}')

    if show_median:
        ax.axvline(median_val, color='green', linestyle='-.',
                   linewidth=2, label=f'Median: {median_val:.2f}')

    # 添加正态分布曲线（如果适用）
    if density and not cumulative:
        from scipy.stats import norm
        xmin, xmax = ax.get_xlim()
        x = np.linspace(xmin, xmax, 100)
        p = norm.pdf(x, mean_val, std_val)
        ax.plot(x, p, 'k', linewidth=2, label='Normal Distribution')

    # 设置图表属性
    ax.set_title(title, fontsize=14, fontweight='bold', pad=20)
    ax.set_xlabel(xlabel, fontsize=12)
    ax.set_ylabel('Density' if density else 'Frequency', fontsize=12)

    ax.grid(True, linestyle='--', alpha=0.3)

    if show_mean or show_median:
        ax.legend(fontsize=10)

    # 添加统计信息文本框
    textstr = f'N = {len(data)}\nMean = {mean_val:.2f}\nStd = {std_val:.2f}'
    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
    ax.text(0.02, 0.98, textstr, transform=ax.transAxes, fontsize=10,
            verticalalignment='top', bbox=props)

    plt.tight_layout()
    return fig, ax, (n, bins, patches)