"""Original concept diagrams and plots of the recorded RL experiments."""
from pathlib import Path
import json
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
from matplotlib.patches import FancyBboxPatch,Rectangle,Circle
import numpy as np
import torch
from deep_diagrams import setup,boxes,TEAL,ORANGE,BLUE
from reinforcement_learning import GridWorld,value_iteration

ROOT=Path(__file__).resolve().parents[1]
DEST=ROOT/"artifacts/rl/figures"


def main():
    setup();DEST.mkdir(parents=True,exist_ok=True);names=[]
    def save(name,fig):
        for ext in ("png","svg"):fig.savefig(DEST/f"{name}.{ext}",bbox_inches="tight",dpi=160)
        plt.close(fig);names.append(name)
    fig,ax=plt.subplots(figsize=(9,4.5),layout="constrained")
    ax.set(xlim=(0,10),ylim=(0,5));ax.axis("off")
    for x,label in [(1,"智能体 Agent\n策略根据观测选动作"),(6,"环境 Environment\n状态随动作和随机性改变")]:
        ax.add_patch(FancyBboxPatch((x,1.5),3,1.7,boxstyle="round,pad=.05",
                     facecolor="#e7f2ef",edgecolor=TEAL))
        ax.text(x+1.5,2.35,label,ha="center",va="center",fontsize=13)
    ax.annotate("",(7.5,3.3),(2.5,3.3),arrowprops={"arrowstyle":"->","connectionstyle":"arc3,rad=-.4","color":ORANGE,"lw":2})
    ax.text(5,4.35,"动作 a(t)：智能体做了什么",ha="center")
    ax.annotate("",(2.5,1.3),(7.5,1.3),arrowprops={"arrowstyle":"->","connectionstyle":"arc3,rad=-.4","color":BLUE,"lw":2})
    ax.text(5,.05,"下一观测 o(t+1) 与奖励 r(t+1)：环境给出的反馈",ha="center")
    save("interaction_loop",fig)
    rewards=[1,0,4];gamma=.5
    fig,axes=plt.subplots(2,1,figsize=(9,4.3),layout="constrained")
    boxes(axes[0],["当前 s0","动作 a0\n得到 r1=1","下一动作\n得到 r2=0","再下一动作\n得到 r3=4"])
    axes[0].set_title("奖励发生在动作之后；回报汇总之后的奖励")
    axes[1].bar(["r1","γ r2","γ² r3"],[1,0,1],color=[TEAL,BLUE,ORANGE])
    axes[1].set(ylabel="折扣后贡献",title="γ=0.5 时 G0 = 1 + 0.5×0 + 0.25×4 = 2")
    save("return_timeline",fig)
    fig,axes=plt.subplots(1,2,figsize=(9,3.7),layout="constrained")
    env=GridWorld();values,q,_=value_iteration(env)
    arr=values.reshape(3,4).numpy()
    for ax in axes:
        ax.imshow(arr,cmap="YlGnBu",vmin=-1,vmax=1)
        ax.set(xticks=range(4),yticks=range(3))
        ax.set_xticks(np.arange(-.5,4,1),minor=True);ax.set_yticks(np.arange(-.5,3,1),minor=True)
        ax.grid(which="minor",color="white",lw=2)
        for s in range(12):
            row,col=divmod(s,4)
            if s in env.walls:
                ax.add_patch(Rectangle((col-.5,row-.5),1,1,color="#666666"))
                ax.text(col,row,"墙",ha="center",va="center",color="white")
            elif s in (env.goal,env.pit):
                ax.text(col,row,"终点" if s==env.goal else "陷阱",ha="center",va="center")
            elif ax is axes[0]:
                ax.text(col,row,f"s={s}\nV*={float(values[s]):.3f}",ha="center",va="center")
            else:
                action=int(q[s].argmax());dr,dc=env.offsets[action]
                ax.arrow(col-.18*dc,row-.18*dr,.34*dc,.34*dr,head_width=.12,color="black")
    axes[0].set_title("已知模型计算的最优折扣价值")
    axes[1].set_title("每格选择最大 Q 值的一种动作")
    save("grid_values_policy",fig)
    fig,ax=plt.subplots(figsize=(9,4),layout="constrained")
    ax.set(xlim=(0,10),ylim=(0,6));ax.axis("off")
    nodes=[(5,5,"当前状态 s"),(2,3.3,"动作 a：均值"),(8,3.3,"动作 b：均值"),
           (1,1.2,"奖励 0\n概率 0.5"),(3.5,1.2,"奖励 4\n概率 0.5"),
           (6.5,1.2,"奖励 1\n概率 1")]
    for x,y,label in nodes:
        ax.text(x,y,label,ha="center",va="center",bbox={"boxstyle":"round","fc":"#e7f2ef","ec":TEAL})
    for a,b in [(0,1),(0,2),(1,3),(1,4),(2,5)]:
        x1,y1,_=nodes[a];x2,y2,_=nodes[b]
        ax.annotate("",(x2,y2+.5),(x1,y1-.35),arrowprops={"arrowstyle":"->","color":BLUE})
    ax.text(8,1,"先对随机结果取期望，\n再对可选动作取最大。\n若后续终止：选 a，期望 2。",ha="center")
    save("bellman_backup",fig)
    fig,axes=plt.subplots(1,2,figsize=(9,3.7),layout="constrained")
    probabilities=np.array([.2,.5,.8])
    axes[0].bar(["机器 A","机器 B","机器 C"],probabilities,color=[BLUE,ORANGE,TEAL])
    axes[0].set(ylim=(0,1),ylabel="真实中奖概率（学习者事先不知道）")
    report=ROOT/"artifacts/rl/tabular/bandit-report.json"
    if report.exists():
        data=json.loads(report.read_text(encoding="utf-8"))
        for key,runs in data["runs"].items():
            a=np.array([r["cumulative_expected_regret"] for r in runs])
            mean,std=a.mean(0),a.std(0,ddof=1)
            axes[1].plot(np.arange(1,a.shape[1]+1),mean,label=f"epsilon={key}")
            axes[1].fill_between(np.arange(1,a.shape[1]+1),mean-std,mean+std,alpha=.15)
    axes[1].set(xlabel="交互步数",ylabel="累计期望遗憾",title="5 个训练种子的均值 ± 样本标准差")
    axes[1].legend();save("bandit_exploration",fig)
    fig,axes=plt.subplots(3,1,figsize=(10,6),layout="constrained")
    boxes(axes[0],["当前 s","完整回合\nr1,r2,...","MC 目标\n实际折扣回报"])
    boxes(axes[1],["当前 s","一步 r、s'","TD 目标\nr+γV(s')"])
    boxes(axes[2],["当前 s,a","一步 r、s'","Q-learning\nr+γ max Q(s',a')"])
    axes[0].set_title("预测目标来自哪里；真正终止时续接项为零")
    save("mc_td_targets",fig)
    fig,axes=plt.subplots(1,2,figsize=(9,3.4),layout="constrained")
    for ax,values,title in [(axes[0],[2,2],"若只看反馈 reward=2，二者相同"),
                            (axes[1],[2,2+.9*5],"价值目标：终止 2，外部截断 6.5")]:
        ax.bar(["任务终止","外部截断"],values,color=[ORANGE,TEAL]);ax.set(title=title,ylabel="数值")
    save("termination_truncation",fig)
    grid=ROOT/"artifacts/rl/tabular/grid-report.json"
    if grid.exists():
        result=json.loads(grid.read_text(encoding="utf-8"))
        fig,axes=plt.subplots(1,2,figsize=(10,3.5),layout="constrained")
        for name,runs in result["methods"].items():
            values=np.array([[e["return"] for e in r["training"]] for r in runs])
            width=30
            smoothed=np.array([np.convolve(v,np.ones(width)/width,mode="valid") for v in values])
            axes[0].plot(np.arange(width,values.shape[1]+1),smoothed.mean(0),label=name)
        axes[0].set(xlabel="训练回合",ylabel="30回合滑动平均实际奖励和",title="训练包含探索，不能等同部署策略")
        axes[0].legend(fontsize=8)
        names_m=list(result["methods"])
        axes[1].bar(names_m,[np.mean([r["evaluation"]["success_rate"] for r in result["methods"][name]]) for name in names_m],color=TEAL)
        axes[1].set(ylim=(0,1.1),ylabel="独立评估成功率",title="固定最终参数，关闭 epsilon 探索")
        save("tabular_results",fig)
    fig,axes=plt.subplots(2,1,figsize=(10,5),layout="constrained")
    boxes(axes[0],["环境交互","回放池\n(s,a,r,s',term)","随机批次","在线 Q 网络\n更新当前动作值"])
    boxes(axes[1],["在线网\n选当前 Q","目标网\n提供续接目标","TD误差\nHuber损失","周期复制\n在线 → 目标"])
    axes[0].set_title("DQN：收集数据与参数更新分开；目标不参与本次反向")
    save("dqn_architecture",fig)
    fig,axes=plt.subplots(2,1,figsize=(10,5),layout="constrained")
    boxes(axes[0],["状态 s","Actor\n动作分布 π","采样动作 a","环境反馈\nr、s'"])
    boxes(axes[1],["Critic\nV(s)、V(s')","TD / GAE\n估计优势","优势停止梯度","加权 logπ\n更新 Actor"])
    axes[0].set_title("Actor 决定怎样做，Critic 估计这一步是否比通常更好")
    save("actor_critic",fig)
    fig,axes=plt.subplots(2,1,figsize=(11,6),layout="constrained")
    for ax in axes:
        ax.set(xlim=(-.2,11),ylim=(-.2,3));ax.axis("off")
    def node(ax,x,y,text,width=1.7):
        ax.add_patch(FancyBboxPatch((x,y),width,.65,boxstyle="round,pad=.04",
                     facecolor="#e7f2ef",edgecolor=TEAL))
        ax.text(x+width/2,y+.325,text,ha="center",va="center",fontsize=10)
    for x,label in [(0,"小车读数\n[B,4]"),(2.3,"Linear 4→64\n+ ReLU"),(4.6,"Linear 64→64\n+ ReLU"),(6.9,"Linear 64→2\nQ: [B,2]")]:
        node(axes[0],x,1,label)
        if x:axes[0].annotate("",(x-.1,1.32),(x-.5,1.32),arrowprops={"arrowstyle":"->","color":BLUE})
    node(axes[0],9.2,1,"按记录动作\n取 Q(s,a)",width=1.5)
    axes[0].annotate("",(9.1,1.32),(8.7,1.32),arrowprops={"arrowstyle":"->","color":BLUE})
    axes[0].set_title("DQN 实际网络：三层全连接；输出价值，不是概率")
    node(axes[1],.3,1,"网格 one-hot\n[B,12]")
    node(axes[1],3.1,1,"共享 Linear 12→32\n+ tanh")
    node(axes[1],6.5,1.8,"策略头 32→4\nlogits [B,4]")
    node(axes[1],6.5,.2,"价值头 32→1\nV(s) [B]")
    node(axes[1],9.1,1.8,"Categorical\n采样 / logπ",width=1.6)
    node(axes[1],9.1,.2,"回归目标\nCritic损失",width=1.6)
    for start,end in [((2.1,1.32),(3,1.32)),((4.9,1.32),(6.4,2.12)),
                       ((4.9,1.32),(6.4,.52)),((8.3,2.12),(9,2.12)),((8.3,.52),(9,.52))]:
        axes[1].annotate("",end,start,arrowprops={"arrowstyle":"->","color":BLUE})
    axes[1].set_title("网格 PPO 实际网络：共享特征，两种输出有不同训练职责")
    save("network_heads",fig)
    fig,ax=plt.subplots(figsize=(10,3.3),layout="constrained")
    boxes(ax,["当前旧回合\nV=1,r=2","截断前观测\nV(next)=5","重置边界\n切断 GAE 迹","新回合\n不连接旧回合"])
    ax.set_title("截断例：δ = 2 + 0.9×5 - 1 = 5.5；用旧下一观测自举，别接入重置后状态")
    save("gae_boundaries",fig)
    ratio=np.linspace(.3,1.7,300);eps=.2
    fig,axes=plt.subplots(1,2,figsize=(9,3.6),layout="constrained")
    for ax,adv in zip(axes,[1,-1]):
        raw=ratio*adv
        clipped=np.minimum(raw,np.clip(ratio,1-eps,1+eps)*adv)
        ax.plot(ratio,raw,"--",color=BLUE,label="未裁剪");ax.plot(ratio,clipped,color=TEAL,label="PPO-Clip")
        ax.axvline(.8,color="gray",lw=.7);ax.axvline(1.2,color="gray",lw=.7)
        ax.set(xlabel="新 / 旧动作概率比",ylabel="待最大化的单项目标",title=f"优势 A={adv}")
        ax.legend()
    save("ppo_clipping",fig)
    fig,ax=plt.subplots(figsize=(10,2.8),layout="constrained")
    boxes(ax,["状态 s","均值 μ\n对数标准差","采样 u=μ+σε","tanh 限幅","缩放到\n动作范围"])
    ax.set_title("SAC 常用有界随机动作：概率计算也要包含变换的体积修正")
    save("continuous_action",fig)
    fig,axes=plt.subplots(2,1,figsize=(10,5),layout="constrained")
    boxes(axes[0],["真实交互","学习环境\n转移 / 奖励","在模型中\n规划或想象","执行动作\n再核对真实环境"])
    boxes(axes[1],["已有交互记录","检查动作\n覆盖范围","固定数据\n优化策略","独立评估\n不能只信估计 Q"])
    axes[0].set_title("基于模型：错误可在多步预测中累积")
    axes[1].set_title("离线学习：未覆盖动作的价值缺少证据")
    save("model_offline",fig)
    inventory=ROOT/"artifacts/rl/tabular/inventory-report.json"
    if inventory.exists():
        data=json.loads(inventory.read_text(encoding="utf-8"))
        fig,ax=plt.subplots(figsize=(7,3.8),layout="constrained")
        a=np.array(data["order_policy_by_remaining_days"])[1:]
        im=ax.imshow(a,origin="lower",cmap="YlGnBu")
        for i in range(a.shape[0]):
            for j in range(a.shape[1]):ax.text(j,i,str(a[i,j]),ha="center",va="center")
        ax.set(xticks=range(5),yticks=range(5),yticklabels=range(1,6),
               xlabel="当前库存",ylabel="剩余天数",title="已知需求模型的最优补货量（表中数字）")
        fig.colorbar(im,ax=ax,label="补货件数");save("inventory_policy",fig)
    fig,ax=plt.subplots(figsize=(10,2.8),layout="constrained")
    boxes(ax,["训练种子\n分别训练","验证场景\n选择设置","冻结方案\n全部种子","独立评估\n固定重置种子","报告交互预算\n与种子差异"])
    ax.set_title("训练回报、验证选择与最终评价分开")
    save("evaluation_protocol",fig)
    (DEST/"figures.json").write_text(json.dumps(names,indent=2),encoding="utf-8")
    print(f"Saved {len(names)} RL figure pairs")


if __name__=="__main__":
    main()
