import sys
import math
import re
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
T = {'titre': 'Plan mundial Artesia 7: la parte de cada tipo de central en la producción', 'sous': '{t} TWh al año producidos por las centrales del plan', 'groupes': ['V14 Soleil', 'V14 de las crestas', 'Paneles híbridos', 'V14 cerca de las subestaciones', 'Todo lo demás'], 'liste': 'El detalle, de mayor a menor (parte de la producción)', 'lignes': ['V14 Soleil de las mesetas', 'V14 de las crestas', 'Paneles solares híbridos industriales', 'V14 cerca de las subestaciones fósiles', 'Pacha existentes', 'V21 Presa al viento', 'V14 Soleil mixtas', 'Islas híbridas flotantes', 'V21 Presa al sol', 'Gold existentes', 'O Sky', 'Torres Titan Claudia costeras (1,000)', 'Torres Titan Claudia Paris Style (500)', 'Pequeñas Gold en manantiales kársticos (8)'], 'pied': 'Las Sky existentes y las V15 Canyon almacenan sin producir.   www.mulo.world, noviembre de 2026, CC BY 4.0', 'dec': '.', 'mil': ',', 'pct': ' %', 'moins': 'menos del 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_7_sites.csv")
t = pd.read_csv(f"{D}/plan_mondial_artesia_7_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["mixte"], w["flottant"], 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[6], v[1], v[2], v[3], tot - v[0] - v[6] - 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, 0, 4, 4, 4, 4, 4, 4, 4]
for i, (val, nom) in enumerate(zip(v, T["lignes"])):
    fort = i in (11, 12)
    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_7.png", dpi=150)
