"""Regenerate the figures from weekly.csv and results.json using Matplotlib."""

import csv
import json
from datetime import date
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
from matplotlib import pyplot as plt
from matplotlib.ticker import PercentFormatter


DIRECTORY = Path(__file__).resolve().parent
INK = "#20231f"
BLUE = "#234ad5"
MUTED = "#696c67"
GRID = "#e1e0da"
plt.rcParams.update({
    "font.family": "DejaVu Sans",
    "font.size": 11,
    "text.color": INK,
    "axes.labelcolor": INK,
    "xtick.color": INK,
    "ytick.color": INK,
    "axes.spines.right": False,
    "axes.spines.top": False,
    "axes.spines.left": False,
    "axes.edgecolor": GRID,
    "axes.axisbelow": True,
})


def weekly_plot(rows, locale):
    tr = locale == "tr"
    fig, ax = plt.subplots(figsize=(6, 3.55), dpi=200)
    fig.subplots_adjust(left=0.13, right=0.97, bottom=0.14, top=0.73)
    weeks = [date.fromisoformat(row["origin"]) for row in rows]
    for key, label, color, style, marker in [
        ("observed_rate", "Gözlenen" if tr else "Observed", INK, "-", "o"),
        ("horizon_rate_mean_probability", "Temel oran" if tr else "Horizon baseline", BLUE, "--", None),
        ("age_rate_mean_probability", "Yaşa göre" if tr else "By deal age", MUTED, ":", None),
    ]:
        ax.plot(weeks, [float(row[key]) for row in rows], label=label,
                color=color, linestyle=style, marker=marker, linewidth=2, markersize=3.2)

    tick_positions = [0, 4, 8, 13, 17]
    labels = ["3 Tem", "31 Tem", "28 Ağu", "2 Eki", "30 Eki"] if tr else [
        "Jul 3", "Jul 31", "Aug 28", "Oct 2", "Oct 30"
    ]
    ax.set_xticks([weeks[index] for index in tick_positions], labels)
    ax.set_yticks([0, 0.05, 0.10, 0.15, 0.20, 0.25])
    ax.set_ylim(0, 0.25)
    ax.yaxis.set_major_formatter(PercentFormatter(1, decimals=0))
    ax.grid(axis="y", color=GRID)
    ax.tick_params(length=0, pad=6)
    fig.text(0.055, 0.91, "30 günde kazanılma oranı" if tr else "Wins within 30 days",
             fontsize=16, weight="semibold")
    ax.legend(loc="lower left", bbox_to_anchor=(-0.095, 1.05), ncols=3, frameon=False,
              handlelength=1.7, columnspacing=1.15)
    fig.savefig(DIRECTORY / f"weekly-30d-{locale}.png")
    plt.close(fig)


def age_plot(groups, locale):
    tr = locale == "tr"
    fig, ax = plt.subplots(figsize=(6, 3.55), dpi=200)
    fig.subplots_adjust(left=0.16, right=0.96, bottom=0.14, top=0.74)
    positions = list(range(len(groups)))
    ax.barh([i - 0.16 for i in positions], [row["observed_rate"] for row in groups],
            color=INK, height=0.25, label="Gözlenen" if tr else "Observed")
    ax.barh([i + 0.16 for i in positions],
            [row["models"]["age_rate"]["mean_probability"] for row in groups],
            color=BLUE, height=0.25, label="Yaşa göre tahmin" if tr else "Prediction by age")
    ax.set_yticks(positions, [row["age_group"] for row in groups])
    ax.invert_yaxis()
    ax.set_xticks([0, 0.10, 0.20, 0.30, 0.40])
    ax.set_xlim(0, 0.40)
    ax.xaxis.set_major_formatter(PercentFormatter(1, decimals=0))
    ax.grid(axis="x", color=GRID)
    ax.tick_params(length=0, pad=6)
    fig.text(0.055, 0.91, "Tahmin günündeki fırsat yaşı" if tr else "Deal age at the forecast date",
             fontsize=16, weight="semibold")
    ax.legend(loc="lower left", bbox_to_anchor=(-0.125, 1.06), ncols=2, frameon=False)
    fig.savefig(DIRECTORY / f"age-30d-{locale}.png")
    plt.close(fig)


def main():
    with (DIRECTORY / "weekly.csv").open(encoding="utf-8", newline="") as data:
        rows = [row for row in csv.DictReader(data) if row["horizon"] == "30"]
    result = json.loads((DIRECTORY / "results.json").read_text(encoding="utf-8"))
    thirty_day = next(row for row in result["results"] if row["horizon"] == 30)
    for locale in ("en", "tr"):
        weekly_plot(rows, locale)
        age_plot(thirty_day["age_groups"], locale)


if __name__ == "__main__":
    main()
