#!/usr/bin/env python3
"""Plot the context composition of methylated read calls in a Bismark report."""
import argparse
import csv
from pathlib import Path
import re

import matplotlib.pyplot as plt


def read_counts(report):
    matches = re.findall(
        r"^Total methylated C's in (CpG|CHG|CHH) context:\s+(\d+)",
        Path(report).read_text(), re.MULTILINE,
    )
    counts = {context.replace("CpG", "CG"): int(value) for context, value in matches}
    if len(matches) != 3 or set(counts) != {"CG", "CHG", "CHH"}:
        raise ValueError("Expected exactly one methylated-call total per context")
    if not sum(counts.values()):
        raise ValueError("No methylated calls; a composition pie is undefined")
    return counts


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--report", required=True)
    parser.add_argument("--sample", required=True)
    parser.add_argument("--outdir", type=Path, default=Path("08_plots"))
    args = parser.parse_args()
    counts = read_counts(args.report)
    total = sum(counts.values())
    args.outdir.mkdir(parents=True, exist_ok=True)
    with (args.outdir / f"{args.sample}.context_pie.tsv").open("w", newline="") as handle:
        writer = csv.writer(handle, delimiter="\t")
        writer.writerow(["context", "methylated_calls", "fraction_of_methylated_calls"])
        for context, count in counts.items():
            writer.writerow([context, count, f"{count / total:.8f}"])

    fig, ax = plt.subplots(figsize=(4.5, 4))
    ax.pie(
        counts.values(), labels=counts.keys(), autopct="%1.1f%%",
        startangle=90, colors=["#a47c27", "#477c9b", "#7f9870"],
    )
    ax.set_title(f"{args.sample}\nMethylated-call context composition")
    fig.tight_layout()
    fig.savefig(args.outdir / f"{args.sample}.context_pie.png", dpi=200)
    plt.close(fig)


if __name__ == "__main__":
    main()
