import sys
import math
import re
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = ['Inter', 'Noto Sans CJK SC']
T = {'titre': 'Artesia 7 世界计划：每类电站在发电量中的占比', 'sous': '计划中的电站每年发电 {t} TWh', 'groupes': ['V14 Soleil', '山脊 V14', '混合太阳能板', '变电站附近的 V14', '其余全部'], 'liste': '明细，从大到小（占发电量的比例）', 'lignes': ['高原上的 V14 Soleil', '山脊上的 V14', '工业混合太阳能板', '化石变电站附近的 V14', '现有 Pacha', 'V21 水坝，风力型', '混合型 V14 Soleil', '浮动混合岛', 'V21 水坝，日照型', '现有 Gold', 'O Sky', '海岸 Titan Claudia 塔楼（1,000 座）', 'Titan Claudia Paris Style 塔楼（500 座）', '岩溶泉上的小型 Gold（8 座）'], 'pied': '现有 Sky 和 V15 Canyon 只储能，不发电。   www.mulo.world，2026 年 11 月，CC BY 4.0', 'dec': '.', 'mil': ',', 'pct': '%', 'moins': '不到 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)
