"""Plotting helpers for BABAPPA outputs."""
# ruff: noqa: E402

from __future__ import annotations

import os
import tempfile
from pathlib import Path


def _ensure_writable_mplconfig() -> None:
    if os.environ.get("MPLCONFIGDIR"):
        return
    default = Path.home() / ".matplotlib"
    try:
        default.mkdir(parents=True, exist_ok=True)
        probe = default / ".babappa_write_test"
        probe.write_text("ok", encoding="utf-8")
        probe.unlink(missing_ok=True)
        return
    except OSError:
        pass
    fallback = Path(tempfile.gettempdir()) / "babappa_mplconfig"
    fallback.mkdir(parents=True, exist_ok=True)
    os.environ["MPLCONFIGDIR"] = str(fallback)


_ensure_writable_mplconfig()

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


def plot_null_distribution(observed: float, null_stats: np.ndarray, outpath: str | Path) -> Path:
    out = Path(outpath)
    out.parent.mkdir(parents=True, exist_ok=True)

    plt.figure(figsize=(6, 4))
    plt.hist(null_stats, bins=30, color="#4E79A7", alpha=0.8, edgecolor="white")
    plt.axvline(observed, color="#E15759", linewidth=2, label=f"Observed: {observed:.3f}")
    plt.xlabel("Gene statistic")
    plt.ylabel("Count")
    plt.title("Null distribution vs observed")
    plt.legend()
    plt.tight_layout()
    plt.savefig(out, dpi=180)
    plt.close()
    return out


def plot_site_contributions(site_table: pd.DataFrame, outpath: str | Path) -> Path:
    out = Path(outpath)
    out.parent.mkdir(parents=True, exist_ok=True)

    plt.figure(figsize=(7, 3.5))
    plt.plot(site_table["site"], site_table["contribution"], color="#59A14F", linewidth=1.5)
    plt.xlabel("Codon site")
    plt.ylabel("Contribution")
    plt.title("Site-level contribution profile")
    plt.tight_layout()
    plt.savefig(out, dpi=180)
    plt.close()
    return out


def plot_sensitivity(sensitivity_df: pd.DataFrame, outpath: str | Path) -> Path:
    out = Path(outpath)
    out.parent.mkdir(parents=True, exist_ok=True)

    plt.figure(figsize=(7, 4))
    for gene, sub in sensitivity_df.groupby("gene"):
        plt.plot(sub["scenario"], sub["p_value"], marker="o", linewidth=1.2, label=gene)
    plt.xticks(rotation=45, ha="right")
    plt.ylabel("p-value")
    plt.title("Sensitivity analysis across null settings")
    plt.legend(fontsize=8)
    plt.tight_layout()
    plt.savefig(out, dpi=180)
    plt.close()
    return out
