import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import seaborn as sns
from scipy import stats
from scipy.stats import gaussian_kde

# Path Configuration
# MT5 terminal sandbox default path (Windows):
# C:\Users\<user>\AppData\Roaming\MetaQuotes\Terminal\<InstanceID>\MQL5\Files\
# Adjust DATA_PATH to point to your local MT5 Files directory.

BASE_DIR   = os.path.dirname(os.path.abspath(__file__))
DATA_PATH  = os.path.join(BASE_DIR, "exports", "analytics_export.csv")
OUTPUT_DIR = os.path.join(BASE_DIR, "charts")
os.makedirs(OUTPUT_DIR, exist_ok=True)

# Load the normalized analytics export
df = pd.read_csv(DATA_PATH)

# Global Style Configuration
plt.rcParams.update({
    "figure.facecolor"  : "#0d1117",
    "axes.facecolor"    : "#161b22",
    "axes.edgecolor"    : "#30363d",
    "axes.labelcolor"   : "#c9d1d9",
    "xtick.color"       : "#8b949e",
    "ytick.color"       : "#8b949e",
    "text.color"        : "#c9d1d9",
    "grid.color"        : "#21262d",
    "grid.linestyle"    : "--",
    "grid.linewidth"    : 0.6,
    "font.family"       : "monospace",
    "font.size"         : 9,
})


def plot_drawdown_distribution(df: pd.DataFrame, save_path: str = None):
    """
    Maximum Drawdown Duration and Depth Distribution (Seaborn KDE)

    Generates two KDE distribution overlays on a dual-panel figure:
      Left panel:  KDE of Max_Drawdown_PCT across all records.
      Right panel: KDE of Drawdown_Duration_Bars.

    Parameters
    ----------
    df        : Full analytics DataFrame from CSV export.
    save_path : File path for saving the output figure (optional).
    """

    dd_depth    = df["Max_Drawdown_PCT"].dropna().abs().values
    dd_duration = df["Drawdown_Duration_Bars"].dropna().values

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8.167, 5.0))
    fig.suptitle(
        "Drawdown Distribution Profile  |  Depth and Duration Density Estimation",
        fontsize=11, fontweight="bold", color="#e6edf3"
    )

    # --- Left Panel: Drawdown Depth KDE
    sns.kdeplot(dd_depth, ax=ax1,
                color="#f85149", linewidth=2.2, fill=True, alpha=0.18)
    ax1.set_xlabel("Drawdown Depth (%)", fontsize=9, labelpad=7)
    ax1.set_ylabel("Probability Density", fontsize=9, labelpad=7)
    ax1.set_title("Depth Distribution", fontsize=9, color="#8b949e", pad=6)

    for pct, pct_val in [(50, np.percentile(dd_depth, 50)),
                         (90, np.percentile(dd_depth, 90)),
                         (95, np.percentile(dd_depth, 95))]:
        ax1.axvline(pct_val, color="#d29922", linewidth=0.9, linestyle=":", alpha=0.8)
        ax1.text(pct_val + 0.1, ax1.get_ylim()[1] * 0.92,
                 f"P{pct}: {pct_val:.1f}%", fontsize=6.5, color="#d29922", ha="left")

    ax1.hist(dd_depth, bins=30, density=True,
             color="#f85149", alpha=0.10, edgecolor="none", zorder=0)
    ax1.grid(True, alpha=0.3)
    ax1.spines[["top", "right"]].set_visible(False)

    # --- Right Panel: Drawdown Duration KDE
    sns.kdeplot(dd_duration, ax=ax2,
                color="#388bfd", linewidth=2.2, fill=True, alpha=0.18)
    ax2.set_xlabel("Drawdown Duration (Bars)", fontsize=9, labelpad=7)
    ax2.set_ylabel("Probability Density", fontsize=9, labelpad=7)
    ax2.set_title("Duration Distribution", fontsize=9, color="#8b949e", pad=6)

    for pct, pct_val in [(50, np.percentile(dd_duration, 50)),
                         (90, np.percentile(dd_duration, 90)),
                         (95, np.percentile(dd_duration, 95))]:
        ax2.axvline(pct_val, color="#d29922", linewidth=0.9, linestyle=":", alpha=0.8)
        ax2.text(pct_val + 0.5, ax2.get_ylim()[1] * 0.92,
                 f"P{pct}: {pct_val:.0f}b", fontsize=6.5, color="#d29922", ha="left")

    ax2.hist(dd_duration, bins=30, density=True,
             color="#388bfd", alpha=0.10, edgecolor="none", zorder=0)
    ax2.grid(True, alpha=0.3)
    ax2.spines[["top", "right"]].set_visible(False)

    plt.tight_layout()

    if save_path:
        plt.savefig(save_path, dpi=120, bbox_inches="tight",
                    facecolor=fig.get_facecolor())
    plt.show()


# Execute
plot_drawdown_distribution(
    df,
    save_path=os.path.join(OUTPUT_DIR, "Drawdown_Distribution_KDE.png")
)
