"""Redraw published txt2stop relative risks. Requires matplotlib; see source.txt."""
import csv
import math
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager, ticker

HERE = Path(__file__).resolve().parent
# 使用自己的数据时，一并更新这些标签及 source.txt。
STUDY_TITLE = "txt2stop：不同缺失数据处理下的结果"
OUTCOME_LABEL = "六个月经生化验证的持续戒烟"
COMPARISON_LABEL = "戒烟短信组相对对照组"
SOURCE_NOTE = "数据：Free 等（Lancet，2011）；按论文报告结果重绘。"
font_path = Path("C:/Windows/Fonts/msyh.ttc")
if font_path.exists():
    font_manager.fontManager.addfont(str(font_path))
    plt.rcParams["font.family"] = font_manager.FontProperties(fname=str(font_path)).get_name()
else:
    plt.rcParams["font.sans-serif"] = ["Noto Sans CJK SC", "Microsoft YaHei", "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams["svg.fonttype"] = "path"
with (HERE / "estimates.csv").open(encoding="utf-8-sig", newline="") as handle:
    rows = list(csv.DictReader(handle))
if not rows:
    raise ValueError("结果表没有数据")
for row in rows:
    if not row["analysis"].strip():
        raise ValueError("分析方式不能为空")
    for field in ["rr", "lower", "upper"]:
        row[field] = float(row[field])
        if not math.isfinite(row[field]):
            raise ValueError("RR及区间必须为有限数值")
    if not 0 < row["lower"] <= row["rr"] <= row["upper"]:
        raise ValueError("RR及区间必须为正，且区间应包含点估计")

# 对照图只展示点估计，刻意省略区间，供正文说明其局限。
base = min(row["rr"] for row in rows) - 0.14
span = max(row["rr"] for row in rows) - base
fig, ax = plt.subplots(figsize=(10, max(4.3, len(rows) * 0.75 + 1.8)), layout="constrained")
for index, row in enumerate(rows):
    ax.barh(index, row["rr"] - base, left=base, color="#b5cdcc", height=0.5)
    ax.text(row["rr"] + span * 0.04, index, f"{row['rr']:.2f}", va="center")
ax.set_yticks(range(len(rows)), [row["analysis"] for row in rows])
ax.invert_yaxis()
ax.set_xlim(base, max(row["rr"] for row in rows) + span * 0.3)
ax.set_xlabel(f"RR（截断横轴，起点 {base:.2f}）")
ax.set_title("只显示点估计时，区间信息缺席", loc="left", fontsize=15, pad=18)
ax.spines[["top", "right"]].set_visible(False)
fig.supxlabel(SOURCE_NOTE, fontsize=10, color="#55606c")
for suffix in ["png", "svg"]:
    fig.savefig(HERE / f"before.{suffix}", dpi=180, bbox_inches="tight", facecolor="white")
plt.close(fig)

fig, (ax, values_ax) = plt.subplots(1, 2, figsize=(11, max(5.2, len(rows) * 0.8 + 2.2)), gridspec_kw={"width_ratios": [4.2, 1.9]}, layout="constrained")
for index, row in enumerate(rows):
    ax.errorbar(row["rr"], index, xerr=[[row["rr"] - row["lower"]], [row["upper"] - row["rr"]]], fmt="o", color="#176b6a", ecolor="#345b66", capsize=4, markersize=7, linewidth=1.8)
    values_ax.text(0.02, index, f"{row['rr']:.2f}  [{row['lower']:.2f}, {row['upper']:.2f}]", va="center", fontsize=11)
ax.axvline(1, color="#6b7280", linestyle="--", linewidth=1.1)
ax.set_xscale("log")
axis_min = min(0.8, min(row["lower"] for row in rows) / 1.15)
axis_max = max(3.1, max(row["upper"] for row in rows) * 1.15)
ax.set_xlim(axis_min, axis_max)
ticks = [x for x in [0.125, 0.25, 0.5, 1, 1.5, 2, 2.5, 3, 4, 8, 16, 32] if axis_min <= x <= axis_max]
ax.set_xticks(ticks)
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(ticker.NullFormatter())
ax.set_yticks(range(len(rows)), [row["analysis"] for row in rows])
ax.set_ylim(len(rows) - 0.4, -0.6)
ax.set_xlabel("RR（对数坐标）\n" + COMPARISON_LABEL, labelpad=12)
ax.grid(axis="x", alpha=0.13)
ax.spines[["top", "right", "left"]].set_visible(False)
values_ax.set_ylim(len(rows) - 0.4, -0.6)
values_ax.set_xlim(0, 1)
values_ax.axis("off")
values_ax.set_title("RR  [95% 置信区间]", fontsize=11, loc="left")
fig.suptitle(STUDY_TITLE + "\n" + OUTCOME_LABEL, fontsize=15, x=0.02, ha="left", linespacing=1.6)
fig.supxlabel(SOURCE_NOTE + "\n三行属于同一试验的不同分析，不作合并。", fontsize=10, color="#55606c", linespacing=1.8)
for suffix in ["png", "svg", "pdf"]:
    fig.savefig(HERE / f"forest.{suffix}", dpi=180, bbox_inches="tight", facecolor="white")
plt.close(fig)
print("Generated before.png, before.svg, forest.png, forest.svg, forest.pdf")
