
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

def plot_binning(bin_stats, feature_name, show=True, filename=None):
    """
    Visualize binning results with dual-axis chart (Count vs Bad Rate).
    bin_stats: list of dicts from BinningProcess
    """
    if not bin_stats:
        print(f"No binning stats available for {feature_name}")
        return

    df_stats = pd.DataFrame(bin_stats)
    
    # Create label
    df_stats['label'] = df_stats.apply(lambda x: f"[{x['min']}, {x['max']})", axis=1)
    
    # Plotting
    fig, ax1 = plt.subplots(figsize=(10, 6))
    
    # Bar chart for Total Count
    ax1.bar(df_stats.index, df_stats['total'], color='skyblue', alpha=0.6, label='Count')
    ax1.set_ylabel('Sample Count', color='blue')
    ax1.tick_params(axis='y', labelcolor='blue')
    ax1.set_xticks(df_stats.index)
    ax1.set_xticklabels(df_stats['label'], rotation=45, ha='right')
    ax1.set_xlabel('Bin')
    
    # Line chart for Bad Rate
    ax2 = ax1.twinx()
    ax2.plot(df_stats.index, df_stats['bad_rate'], color='red', marker='o', linestyle='-', linewidth=2, label='Bad Rate')
    ax2.set_ylabel('Bad Rate', color='red')
    ax2.tick_params(axis='y', labelcolor='red')
    
    # Add IV info
    total_iv = df_stats['iv'].sum()
    plt.title(f"Binning: {feature_name} (IV: {total_iv:.4f})")
    
    # Layout
    plt.tight_layout()
    
    if filename:
        plt.savefig(filename)
        
    if show:
        plt.show()
    else:
        plt.close()
