"""M15 教学图：月度确认和全自动维护的时间，以及订单占净值的闸门。

两张图都是给定的小时和百分比。不连接券商，也不发单。
"""

from __future__ import annotations

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False

OUT = Path(__file__).resolve().parent / "hours_and_caps.png"


def main() -> None:
    semi = 12 * 0.5
    build = 40.0
    maintain = 12 * 1.0
    print("semi_year", f"{semi:.1f}")
    print("auto_year1", f"{build + maintain:.1f}")
    print("auto_year2", f"{maintain:.1f}")
    # 每月维护 1 小时已经多于每月确认 0.5 小时，时间上没有回本点。
    print("payback_if_maintain_1h", "none")
    print("payback_if_maintain_0", f"{build / semi:.3f}")

    nav = 100_000.0
    order_cap = 0.05 * nav
    name_cap = 0.10 * nav
    order = 6_000.0
    held = 8_000.0
    buy = 3_000.0
    print("order_cap", f"{order_cap:.0f}", "order", f"{order:.0f}", "over", order > order_cap)
    print(
        "name_after", f"{held + buy:.0f}",
        "name_cap", f"{name_cap:.0f}",
        "over", held + buy > name_cap,
    )
    cash = 1_000.0
    unsettled_sell = 500.0
    wanted_buy = 1_200.0
    print("buy_vs_cash", f"{wanted_buy:.0f}", f"{cash:.0f}", "needs_unsettled", wanted_buy > cash)

    fig, axes = plt.subplots(1, 2, figsize=(11.2, 4.8))
    ax = axes[0]
    labels = ["半自动\n每年", "全自动\n第一年", "全自动\n此后每年"]
    hours = [semi, build + maintain, maintain]
    ax.bar(labels, hours, color=["#1f4e79", "#a33b3b", "#c4a35a"])
    ax.set_ylabel("小时")
    ax.set_title("确认 0.5 小时，维护 1 小时，搭建 40 小时")
    ax = axes[1]
    sizes = np.array([2, 5, 6, 8, 11], dtype=float)
    colors = ["#5b8e7d" if size <= 5 else "#a33b3b" for size in sizes]
    ax.bar([str(int(size)) for size in sizes], sizes, color=colors)
    ax.axhline(5.0, color="#1f4e79", linestyle="--", label="单笔 5%")
    ax.axhline(10.0, color="#c4a35a", linestyle=":", label="单名 10%")
    ax.set_xlabel("订单占净值（%）")
    ax.set_ylabel("占净值（%）")
    ax.set_title("示例上限：超过 5% 的单笔被标出")
    ax.legend(frameon=False)
    fig.suptitle("M15 时间与额度：政策示例，不是成交")
    fig.tight_layout()
    fig.savefig(OUT, dpi=140)
    print("wrote", OUT)


if __name__ == "__main__":
    main()
