import sys
import math
import re
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
T = {'titre': 'Plan mondial Artesia 8 : la part de chaque type de centrale dans la production', 'sous': '{t} TWh par an produits par les centrales du plan', 'groupes': ['V14 Soleil', 'V14 des crêtes', 'Panneaux hybrides', 'V14 près des postes', 'Tout le reste'], 'liste': 'Le détail, du plus grand au plus petit (part de la production)', 'lignes': ['V14 Soleil des plateaux', 'V14 des crêtes', 'Panneaux solaires hybrides industriels', 'V14 près des postes fossiles', 'Pacha existantes', 'V21 Barrage au vent', 'Îles hybrides flottantes', 'V11 des collines', 'V14 Soleil mixtes', 'V21 Barrage au soleil', 'Gold existantes', 'O Sky', 'Tours Titan Claudia côtières (1 000)', 'Tours Titan Claudia Paris Style (500)', 'Petites Gold sur sources karstiques (8)'], 'pied': 'Sky existantes et V15 Canyon stockent sans produire.   www.mulo.world, novembre 2026, CC BY 4.0', 'dec': ',', 'mil': ' ', 'pct': ' %', 'moins': 'moins de 0,01 %', 'rtl': False}
D = sys.argv[1] if len(sys.argv) > 1 else "."
SORTIE = sys.argv[2] if len(sys.argv) > 2 else "."
s = pd.read_csv(f"{D}/plan_mondial_artesia_8_sites.csv")
t = pd.read_csv(f"{D}/plan_mondial_artesia_8_totaux.csv", index_col=0).valeur
w = s.groupby("type").twh_pris.sum()
v = [w["soleil"], w["crete"], t["hyb_twh"], w["poste"], 420.0, w["v21v"], w["flottant"], w["v11"], w["mixte"], w["v21"], 63.0, 56.0, 43.0 * 39.3 / 43.4, 43.0 * 4.1 / 43.4, w["gold4"]]
tot = sum(v)
def sh(x):
    if not T["rtl"]:
        return x
    return "‏" + re.sub(r"(\d[\d,.]*%)", "⁦\\1⁩", x)
def nb(x, d=0):
    r = f"{x:,.{d}f}".replace(",", "§").replace(".", T["dec"]).replace("§", T["mil"])
    return r
def pc(x):
    p = 100 * x / tot
    if p < 0.01:
        return T["moins"]
    return nb(p, 1 if p >= 1 else 2) + T["pct"]
fig = plt.figure(figsize=(16, 9.6), dpi=150)
fig.patch.set_facecolor("white")
fig.text(0.5, 0.955, sh(T["titre"]), ha="center", va="center", fontsize=19, weight="bold", color="#1f4e8c")
fig.text(0.5, 0.915, sh(T["sous"].format(t=nb(tot))), ha="center", va="center", fontsize=13.5, color="#52514e")
g = [v[0] + v[8], v[1], v[2], v[3], tot - v[0] - v[8] - v[1] - v[2] - v[3]]
col = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4"]
ax = fig.add_axes([0.02, 0.08, 0.44, 0.78])
ax.pie(g, colors=col, startangle=90, counterclock=False, wedgeprops=dict(edgecolor="white", linewidth=2))
ax.set_aspect("equal")
a0 = 90.0
for val, nom in zip(g, T["groupes"]):
    a = a0 - 360 * val / tot / 2
    a0 -= 360 * val / tot
    x, y = math.cos(math.radians(a)), math.sin(math.radians(a))
    r = 0.55 if val / tot > 0.3 else 1.3
    ax.text(r * x, r * y, sh(nom) + "\n" + pc(val), ha="center", va="center", fontsize=12.5, weight="bold", color="white" if r < 1 else "#222222", linespacing=1.3)
ax.set_xlim(-1.75, 1.15)
ax.set_ylim(-1.45, 1.45)
b = fig.add_axes([0.5, 0.08, 0.48, 0.78])
b.set_xlim(0, 1)
b.set_ylim(len(v) + 0.6, -1.1)
b.axis("off")
b.text(1 if T["rtl"] else 0, -0.75, sh(T["liste"]), ha="right" if T["rtl"] else "left", va="center", fontsize=12.5, weight="bold", color="#222222")
grp = [0, 1, 2, 3, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4]
for i, (val, nom) in enumerate(zip(v, T["lignes"])):
    fort = i in (12, 13)
    bw = max(0.42 * val / v[0], 0.004)
    if T["rtl"]:
        b.text(1, i, sh(nom), ha="right", va="center", fontsize=11.5, weight="bold" if fort else "normal", color="#222222")
        b.add_patch(plt.Rectangle((0.42 - bw, i - 0.28), bw, 0.56, color=col[grp[i]], lw=0))
        b.text(0.42 - bw - 0.012, i, sh(pc(val)), ha="right", va="center", fontsize=11.5, weight="bold" if fort else "normal", color="#222222")
    else:
        b.text(0, i, nom, ha="left", va="center", fontsize=11.5, weight="bold" if fort else "normal", color="#222222")
        b.add_patch(plt.Rectangle((0.5, i - 0.28), bw, 0.56, color=col[grp[i]], lw=0))
        b.text(0.5 + bw + 0.012, i, pc(val), ha="left", va="center", fontsize=11.5, weight="bold" if fort else "normal", color="#222222")
if T["rtl"]:
    fig.text(0.98, 0.03, sh(T["pied"]), ha="right", va="center", fontsize=11, color="#52514e")
    fig.text(0.02, 0.03, "www.mulo.world, 2026, CC BY 4.0", ha="left", va="center", fontsize=11, color="#52514e")
else:
    fig.text(0.5, 0.03, T["pied"], ha="center", va="center", fontsize=11, color="#52514e")
fig.savefig(f"{SORTIE}/camembert_centrales_plan_mondial_artesia_8.png", dpi=150)
