#!/usr/bin/env python3
"""Три простых графика по данным Bank Customer Churn Predictions."""
import csv
from collections import Counter
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

# ---------- данные ----------
rows = []
with open("data.csv", newline="", encoding="utf-8") as f:
    for r in csv.DictReader(f):
        r["age"] = int(r["age"])
        r["churn"] = int(r["churn"])
        rows.append(r)

N = len(rows)
churned = sum(r["churn"] for r in rows)
stayed = N - churned
rate = churned / N

# ----------rcParams / стиль ----------
plt.rcParams.update({
    "font.family": "DejaVu Sans",
    "font.size": 11,
    "axes.edgecolor": "#c9ced6",
    "axes.linewidth": 0.8,
    "axes.labelcolor": "#333333",
    "xtick.color": "#555555",
    "ytick.color": "#555555",
    "axes.grid": True,
    "grid.color": "#e6e8ec",
    "grid.linewidth": 0.7,
    "figure.facecolor": "white",
    "axes.facecolor": "white",
})
INK = "#1f2937"
MUTED = "#6b7280"
RED = "#d1495b"
GREEN = "#2a9d8f"
BLUE = "#2e6f9e"
GRAY = "#9aa3ae"

# ---------- 1. Общий отток ----------
fig, ax = plt.subplots(figsize=(9.2, 5.2), dpi=170)
vals = [churned, stayed]
cols = [RED, "#d7dee8"]
labels = [
    f"Ушли (churn=1)\n{churned:,} · {churned/N*100:.1f}%".replace(",", " "),
    f"Остались (churn=0)\n{stayed:,} · {stayed/N*100:.1f}%".replace(",", " "),
]
wedges, _ = ax.pie(vals, colors=cols, startangle=90, counterclock=False,
                   wedgeprops=dict(width=0.36, edgecolor="white", linewidth=2))
ax.text(0, 0.08, f"{rate*100:.1f}%", ha="center", va="center",
        fontsize=36, fontweight="bold", color=RED)
ax.text(0, -0.16, "общий отток", ha="center", va="center", fontsize=12, color=MUTED)
ax.legend(wedges, labels, loc="center left", bbox_to_anchor=(1.0, 0.5),
          frameon=False, fontsize=11, labelspacing=1.3)
ax.set_title("Общий отток клиентов", fontsize=17, fontweight="bold", color=INK, pad=18)
ax.text(0.01, -0.045, f"Всего клиентов: {N:,}   ·   ушло: {churned:,}   ·   осталось: {stayed:,}".replace(",", " "),
        transform=ax.transAxes, ha="left", fontsize=10.5, color=MUTED)
ax.set_aspect("equal")
fig.tight_layout()
fig.savefig("chart_1_overall.png", bbox_inches="tight", facecolor="white")
plt.close(fig)

# ---------- 2. Возраст ----------
df_age = sorted(r["age"] for r in rows)
bins = list(range(18, 76, 4)) + [100]
bin_labels = [f"{bins[i]}–{bins[i+1]-1}" for i in range(len(bins)-1)]
churn_by_bin = Counter()
total_by_bin = Counter()


def bin_index(age):
    for i in range(len(bins) - 1):
        if bins[i] <= age < bins[i + 1]:
            return i
    return len(bins) - 2


for r in rows:
    i = bin_index(r["age"])
    total_by_bin[i] += 1
    churn_by_bin[i] += r["churn"]

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8.4), dpi=170,
                               gridspec_kw={"height_ratios": [1.25, 1], "hspace": 0.42})

age_ch = sorted(r["age"] for r in rows if r["churn"] == 1)
age_st = sorted(r["age"] for r in rows if r["churn"] == 0)
ax1.hist(age_st, bins=range(18, 82, 2), color="#cfd8e3", label=f"Остались (n={stayed:,})".replace(",", " "))
ax1.hist(age_ch, bins=range(18, 82, 2), color=RED, alpha=0.82, label=f"Ушли (n={churned:,})".replace(",", " "))
ax1.set_ylabel("Число клиентов")
ax1.set_xlabel("Возраст, лет")
ax1.set_title("Распределение возраста по клиентам", fontsize=13, fontweight="bold", color=INK, loc="left")
ax1.legend(frameon=False, fontsize=10.5)
ax1.set_xlim(17, 82)
ax1.axvline(42, color=GRAY, lw=1.2, ls="--")
ax1.text(42.6, ax1.get_ylim()[1] * 0.92, "с 42 лет", fontsize=9, color=MUTED)

x = range(len(bin_labels))
rates = [churn_by_bin[i] / total_by_bin[i] * 100 if total_by_bin[i] else 0 for i in range(len(bin_labels))]
bars = ax2.bar(x, rates, color=[RED if r >= 30 else "#e08a95" for r in rates], width=0.72)
ax2.set_xticks(list(x))
ax2.set_xticklabels(bin_labels, rotation=35, ha="right", fontsize=9.5)
ax2.set_ylabel("Доля ушедших, %")
ax2.set_xlabel("Возрастная группа, лет")
ax2.set_title("Доля ушедших по возрастным группам", fontsize=13, fontweight="bold", color=INK, loc="left")
ax2.set_ylim(0, max(rates) * 1.18)
for i, b in enumerate(bars):
    ax2.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.8,
             f"{rates[i]:.1f}%\n(n={total_by_bin[i]})", ha="center", va="bottom", fontsize=8, color=INK)
ax2.yaxis.set_major_formatter(FuncFormatter(lambda v, p: f"{v:.0f}%"))

fig.suptitle("Возраст и отток", fontsize=17, fontweight="bold", color=INK, x=0.01, ha="left")
fig.tight_layout(rect=(0, 0, 1, 0.96))
fig.savefig("chart_2_age.png", bbox_inches="tight", facecolor="white")
plt.close(fig)

# ---------- 3. Отток по странам ----------
countries = ["France", "Germany", "Spain"]
names = {"France": "Франция", "Germany": "Германия", "Spain": "Испания"}
tot = {c: sum(1 for r in rows if r["country"] == c) for c in countries}
ch = {c: sum(r["churn"] for r in rows if r["country"] == c) for c in countries}

fig, ax = plt.subplots(figsize=(10.6, 5.8), dpi=170)
xs = range(len(countries))
bars = ax.bar(xs, [tot[c] for c in countries], width=0.56, color="#dbe3ec", label="Всего клиентов")
bars2 = ax.bar(xs, [ch[c] for c in countries], width=0.56, color=RED, label="Ушли")
for i, c in enumerate(countries):
    ax.text(i, tot[c] + 90, f"всего {tot[c]:,}".replace(",", " "), ha="center", fontsize=9.5, color=MUTED)
    ax.text(i, ch[c] / 2, f"{ch[c]}\n", ha="center", va="center", fontsize=10.5, color="white", fontweight="bold")
    ax.text(i, tot[c] + 330, f"отток {ch[c]/tot[c]*100:.1f}%", ha="center", fontsize=13,
            color=RED, fontweight="bold")
ax.set_xticks(list(xs))
ax.set_xticklabels([f"{names[c]}\n(n={tot[c]:,})".replace(",", " ") for c in countries], fontsize=11)
ax.set_ylabel("Число клиентов")
ax.set_xlabel("Страна")
ax.set_title("Отток по странам", fontsize=17, fontweight="bold", color=INK, loc="left", pad=14)
ax.set_ylim(0, max(tot.values()) * 1.28)
ax.legend(frameon=False, fontsize=10.5, loc="upper left")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig("chart_3_country.png", bbox_inches="tight", facecolor="white")
plt.close(fig)

print("done", N, churned, f"{rate*100:.2f}%")
for c in countries:
    print(c, tot[c], ch[c], f"{ch[c]/tot[c]*100:.2f}%")
