import sys
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
D = sys.argv[1] if len(sys.argv) > 1 else ".."
SORTIE = sys.argv[2] if len(sys.argv) > 2 else "."
o = pd.read_csv(f"{D}/prix_lignes_electriques_pays.csv")
PN = pd.read_csv(f"{SORTIE}/prix_lignes_electriques_pays.csv").set_index("iso").country.to_dict()
e = pd.read_csv(f"{D}/electricite_pays_prix_part_fossile.csv")[["iso", "fossile_twh"]]
o = o.merge(e, on="iso").sort_values("fossile_twh", ascending=False).head(30).iloc[::-1]
fig, g = plt.subplots(figsize=(12, 11))
col = ["#c0392b" if s.startswith("projet") else "#8e44ad" if "souterrain" in s else "#1f5fa8" for s in o.source_facteur]
g.barh([PN[i] for i in o.iso], o.ligne_1000km_meur_gw, color=col)
for y, (v, f) in enumerate(zip(o.ligne_1000km_meur_gw, o.facteur)):
    g.text(v + 15, y, f"{v:,.0f} M€ (factor {f:.2f})", va="center", fontsize=8.5)
g.axvline(500, color="black", ls="--", lw=1)
g.text(1300, 29.2, "Dashes: cautious European price used so far, 500 M€", fontsize=8.5)
g.set_xlabel("Cost of a 1,000 km direct current line, converters included, in M€ per GW")
g.set_xlim(0, 3200)
g.plot([], [], color="#c0392b", lw=6, label="Based on a real project in the country")
g.plot([], [], color="#8e44ad", lw=6, label="Underground required by law (SuedLink)")
g.plot([], [], color="#1f5fa8", lw=6, label="World Bank price level")
g.legend(loc="lower right", fontsize=9)
g.set_title("The price of a large power line in the top 30 fossil countries", fontsize=12)
g.grid(axis="x", alpha=0.3)
fig.tight_layout()
fig.savefig(f"{SORTIE}/schema_prix_lignes_electriques_pays.png", dpi=110)
