import sys
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.ticker
dossier = sys.argv[1] if len(sys.argv) > 1 else ".."
SORTIE = sys.argv[2] if len(sys.argv) > 2 else "."
t = pd.read_csv(f"{dossier}/electricite_pays_prix_part_fossile.csv")
P = dict(zip(t.pays, pd.read_csv(f"{SORTIE}/electricite_pays_prix_part_fossile.csv").country))
F = t.fossile_twh.sum()
a = t.sort_values("fossile_twh", ascending=False).head(25).iloc[::-1]
t["surplus"] = t.artesia_4_twh - t.fossile_twh
b = t.sort_values("surplus", ascending=False).head(15).iloc[::-1]
fig, (g1, g2) = plt.subplots(1, 2, figsize=(16, 10), gridspec_kw={"width_ratios": [1.15, 1]})
y = range(len(a))
g1.barh([i + 0.2 for i in y], a.fossile_twh, height=0.4, color="#5b5b5b", label="Fossil electricity today (TWh/yr)")
g1.barh([i - 0.2 for i in y], a.artesia_4_twh, height=0.4, color="#2e8b57", label="Production placed in the country by Artesia 4 (TWh/yr)")
g1.set_yticks(list(y))
g1.set_yticklabels([f"{P.get(p, p)} ({q:.0f}%)" for p, q in zip(a.pays, a.part_fossile_pct)])
g1.set_xscale("symlog", linthresh=100)
g1.set_xticks([0, 50, 100, 300, 1000, 3000, 6000])
g1.set_xticklabels(["0", "50", "100", "300", "1,000", "3,000", "6,000"])
g1.set_title(f"The top 25 fossil countries ({100 * a.fossile_twh.sum() / F:.0f}% of the world's {F:,.0f} fossil TWh)\nin brackets: fossil share of their electricity", fontsize=11)
g1.set_xlabel("TWh per year, logarithmic scale above 100")
g1.legend(loc="lower right", fontsize=9)
g1.grid(axis="x", alpha=0.3)
y2 = range(len(b))
g2.barh([i + 0.2 for i in y2], b.fossile_twh, height=0.4, color="#5b5b5b", label="Fossil electricity today")
g2.barh([i - 0.2 for i in y2], b.artesia_4_twh, height=0.4, color="#2e8b57", label="Artesia 4 production")
g2.barh([i - 0.2 for i in y2], b.demande_twh, height=0.12, color="#e0a030", label="The country's total consumption")
g2.set_yticks(list(y2))
g2.set_yticklabels([P.get(p, p) for p in b.pays])
g2.set_title("The 15 countries where Artesia 4 produces the most beyond\ntheir fossil electricity (TWh/yr)", fontsize=11)
g2.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v, _: f"{v:,.0f}"))
g2.legend(loc="lower right", fontsize=9)
g2.grid(axis="x", alpha=0.3)
fig.suptitle("Fossil electricity country by country and the production Artesia 4 places there (Ember, latest known year)", fontsize=13)
fig.tight_layout(rect=[0, 0, 1, 0.96])
fig.savefig(f"{SORTIE}/schema_electricite_pays_prix_part_fossile.png", dpi=110)
