#!/usr/bin/env python3
"""Draw deterministic teaching curves; these are not experimental M-bias data."""
import csv
import json
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties


ROOT = Path(__file__).resolve().parents[1]
FONT = FontProperties(fname="/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc")
SOURCE = (
    "https://sequencing.qcfail.com/articles/library-end-repair-reaction-"
    "introduces-methylation-biases-in-paired-end-pe-bisulfite-seq-applications/"
)


def main():
    positions = list(range(1, 151))
    r1 = [70.0] * 150
    r2 = [3.0, 3.0] + [70.0] * 148
    summary = ROOT / "10_summary"
    figures = ROOT / "08_plots"
    summary.mkdir(exist_ok=True)
    figures.mkdir(exist_ok=True)
    with (summary / "mbias_end_repair_simulation.tsv").open("w") as handle:
        writer = csv.writer(handle, delimiter="\t")
        writer.writerow(["read_position", "simulated_R1_pct", "simulated_R2_pct"])
        writer.writerows(zip(positions, r1, r2))
    (summary / "mbias_end_repair_simulation.json").write_text(
        json.dumps(
            {
                "data_kind": "deterministic_teaching_example",
                "experimental_data": False,
                "read_length_bp": 150,
                "R1_pct_all_positions": 70,
                "R2_pct_positions_1_2": 3,
                "R2_pct_positions_3_150": 70,
                "random_sampling": False,
                "source": SOURCE,
                "source_reported_levels_pct": [70, 3],
                "source_curve_digitized": False,
                "note": "The two affected cycles and all curve values are illustrative.",
            },
            indent=2,
        ) + "\n"
    )
    plt.rcParams.update({"font.family": FONT.get_name(), "pdf.fonttype": 42})
    fig, axes = plt.subplots(1, 2, figsize=(11.6, 4.5), layout="constrained")
    for ax, stop, title in zip(axes, [150, 12], ["全部 150 个位置", "放大前 12 个位置"]):
        ax.axvspan(0.5, 2.5, color="#f4e1d2", label="R2 模拟异常区")
        ax.plot(positions[:stop], r1[:stop], color="#416451", lw=2.6, label="R1：模拟正常区域")
        ax.plot(positions[:stop], r2[:stop], color="#b45e3c", lw=2, ls="--", label="R2：模拟末端修复偏差")
        ax.set(xlim=(0.5, stop + 0.5), ylim=(0, 100), xlabel="read 内位置（bp）", ylabel="CpG 甲基化率（%）", title=title)
        ax.grid(axis="y", color="#e5e7e2", lw=0.7)
        ax.spines[["top", "right"]].set_visible(False)
    axes[1].set_xticks([1, 2, 4, 6, 8, 10, 12])
    axes[0].legend(loc="lower right", fontsize=9, frameon=False)
    fig.suptitle("模拟 M-bias：高质量读出也可能包含人为低甲基化", fontsize=16)
    fig.supxlabel("人工设定的教学曲线，无实验计数；不属于本教程样本，也未描摹原始案例曲线。", fontsize=10)
    for suffix in ["png", "pdf"]:
        fig.savefig(figures / f"mbias_end_repair_simulation.{suffix}", dpi=180)
    plt.close(fig)
    print("Teaching figure and parameter tables written; experimental data were not used.")


if __name__ == "__main__":
    main()
