"""Render the aligned high-return experiment and order-path evidence."""

import json
import zipfile
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np


ROOT = Path(__file__).resolve().parent


def backtest_payload(path: Path):
    with zipfile.ZipFile(path) as archive:
        name = next(n for n in archive.namelist() if n.endswith(".json") and "_config" not in n)
        return json.loads(archive.read(name))


recent = backtest_payload(ROOT / "recent30.zip")["strategy"]
pyramid = backtest_payload(ROOT / "pyramid-train.zip")["strategy"]
ewmac = backtest_payload(ROOT / "ewmac-train.zip")["strategy"]["MultiSpeedEwmac1hV1"]
audit = json.loads((ROOT / "recent-order-scaling.json").read_text())
comparison = audit["recent30_backtest_vs_live_database"]

fig, axes = plt.subplots(1, 3, figsize=(16, 5.3), constrained_layout=True)
fig.suptitle("15% monthly target: recent ledger, aligned backtests, and first divergence", fontsize=15, weight="bold")

labels = ["Live ledger\n30d realized", "D48\nflat-start", "ADX\n1x", "ADX\n2x", "ADX\n3x", "ADX\n4x"]
keys = [
    "VolatilityBreakoutRiskCapMatchedBaseline",
    "VolatilityBreakoutRiskCapAdxScaledRisk",
    "VolatilityBreakoutRiskCapAdxScaledRisk2x",
    "VolatilityBreakoutRiskCapAdxScaledRisk3x",
    "VolatilityBreakoutRiskCapAdxScaledRisk4x",
]
values = [audit["windows"]["30d"]["realized"]["monthly_return_fraction"] * 100]
values.extend(recent[key]["profit_total"] * 100 for key in keys)
colors = ["#2b8a3e" if value >= 0 else "#c92a2a" for value in values]
axes[0].bar(np.arange(len(values)), values, color=colors)
axes[0].axhline(15, color="#5f3dc4", linestyle="--", linewidth=1.5, label="15% target")
axes[0].axhline(0, color="#495057", linewidth=0.8)
axes[0].set_xticks(np.arange(len(values)), labels, rotation=20, ha="right")
axes[0].set_ylabel("Return (%)")
axes[0].set_title("Recent 30-day evidence")
axes[0].set_ylim(-23, 17)
axes[0].legend(frameon=False)
for i, value in enumerate(values):
    axes[0].text(i, value + (0.7 if value >= 0 else -1.1), f"{value:.2f}%", ha="center", va="bottom" if value >= 0 else "top", fontsize=9)

train_labels = ["D48 baseline", "Turtle pyramid", "1h EWMAC"]
train_returns = [
    pyramid["VolatilityBreakoutRiskCap"]["profit_total"] * 100,
    pyramid["VolatilityBreakoutRiskCapTurtlePyramidV1"]["profit_total"] * 100,
    ewmac["profit_total"] * 100,
]
train_dd = [
    pyramid["VolatilityBreakoutRiskCap"]["max_drawdown_account"] * 100,
    pyramid["VolatilityBreakoutRiskCapTurtlePyramidV1"]["max_drawdown_account"] * 100,
    ewmac["max_drawdown_account"] * 100,
]
x = np.arange(3)
width = 0.36
axes[1].bar(x - width / 2, train_returns, width, label="return", color="#1971c2")
axes[1].bar(x + width / 2, train_dd, width, label="max DD", color="#f08c00")
axes[1].axhline(0, color="#495057", linewidth=0.8)
axes[1].set_xticks(x, train_labels, rotation=15, ha="right")
axes[1].set_ylabel("Percent")
axes[1].set_title("Training gates for new paths")
axes[1].legend(frameon=False)

attr = comparison["attribution"]
path_labels = ["14 matched\nentries", "Unmatched\npaths"]
live = [attr["same_pair_and_entry_live_profit"], attr["unmatched_live_profit"]]
bt = [attr["same_pair_and_entry_backtest_profit"], attr["unmatched_backtest_profit"]]
x = np.arange(2)
axes[2].bar(x - width / 2, live, width, label="live ledger", color="#2b8a3e")
axes[2].bar(x + width / 2, bt, width, label="flat-start BT", color="#c92a2a")
axes[2].axhline(0, color="#495057", linewidth=0.8)
axes[2].set_xticks(x, path_labels)
axes[2].set_ylabel("PnL (USDT)")
axes[2].set_title("Why 42 trades != the same path")
axes[2].legend(frameon=False)
axes[2].text(0.02, 0.98, "88.3% of PnL gap comes from\ndifferent trade composition", transform=axes[2].transAxes, ha="left", va="top", fontsize=10)

for axis in axes:
    axis.grid(axis="y", alpha=0.22)
    axis.spines[["top", "right"]].set_visible(False)

fig.savefig(ROOT / "high-return-evidence.png", dpi=180)
