import sys
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from global_land_mask import globe
D = sys.argv[1] if len(sys.argv) > 1 else ".."
g = pd.read_csv(f"{D}/postes_noeuds.csv")
c = pd.read_csv(f"{D}/postes_artesia_4_centrales.csv")
r = pd.read_csv(f"{D}/postes_fossiles_liberes_pays.csv")
q = pd.read_csv(f"{D}/reseaux_artesia_4_pays.csv")
fig = plt.figure(figsize=(16, 13))
g1 = fig.add_axes([0.03, 0.38, 0.94, 0.57])
la, lo = np.meshgrid(np.arange(-60, 85, 0.5), np.arange(-180, 180, 0.5), indexing="ij")
g1.imshow(np.where(globe.is_land(la, lo), 1.0, np.nan), extent=[-180, 180, -60, 85], origin="lower", cmap="Greys", vmin=0, vmax=4, aspect="auto")
f = g[g.libere_gw > 0]
a = g[g.libere_gw == 0]
g1.scatter(a.longitude, a.latitude, s=3, color="#1f5fa8", alpha=0.5, label=f"{len(a):,}" + " substations of dams, nuclear plants, wind and solar of 100 MW and more")
g1.scatter(f.longitude, f.latitude, s=f.libere_gw * 6, color="#c0392b", alpha=0.35, lw=0, label=f"{len(f):,}" + " fossil substations of 50 MW and more, freed at closure (size by GW)")
n = c[c.sorte == "aucun"]
g1.scatter(n.lon, n.lat, s=2, color="#7f8c8d", alpha=0.4, label="Artesia 4 plants more than 50 km from any substation")
o = c[c.sorte == "autre"]
g1.scatter(o.lon, o.lat, s=4, color="#2e8b57", alpha=0.7, label="Artesia 4 plants connected to an existing non-fossil substation")
h = c[c.sorte == "fossile"]
g1.scatter(h.lon, h.lat, s=10, color="#f1c40f", edgecolors="black", lw=0.3, label="Artesia 4 plants connected to a freed fossil substation")
x0, y0 = -42, -52
k = 2000 / 111.32
g1.plot([x0, x0 + k], [y0, y0], color="black", lw=3)
g1.plot([x0, x0], [y0 - 1, y0 + 1], color="black", lw=2)
g1.plot([x0 + k, x0 + k], [y0 - 1, y0 + 1], color="black", lw=2)
g1.text(x0 + k / 2, y0 + 2, "2,000 km (at the equator)", ha="center", fontsize=9)
g1.set_xlim(-180, 180)
g1.set_ylim(-60, 85)
g1.set_xticks([])
g1.set_yticks([])
g1.legend(loc="lower left", fontsize=8.5, framealpha=0.9, markerscale=1.5)
g1.set_title("Existing electrical substations (WRI global power plant database) and Artesia 4 plants within 50 km", fontsize=12)
g2 = fig.add_axes([0.12, 0.05, 0.84, 0.26])
noms = ["Chine", "Japon", "Corée du Sud", "Indonésie", "Taïwan", "Inde", "Viêt Nam", "Malaisie", "Thaïlande", "Australie", "Philippines"]
noms_en = ["China", "Japan", "South Korea", "Indonesia", "Taiwan", "India", "Vietnam", "Malaysia", "Thailand", "Australia", "Philippines"]
q = q.set_index("pays")
r = r.set_index("pays")
y = np.arange(len(noms))[::-1]
manque = [max(q.non_couvert_twh.get(p, 0), 0) for p in noms]
capa = [r.reste_gw.get(p, 0) * 8.76 * 0.5 for p in noms]
g2.barh(y + 0.2, manque, height=0.4, color="#8e44ad", label="Fossil electricity without an Artesia 4 plant in reach (TWh/yr)")
g2.barh(y - 0.2, capa, height=0.4, color="#c0392b", label="What the country's freed fossil substations can carry (TWh/yr, lines used at 50%)")
g2.set_yticks(y)
g2.set_yticklabels(noms_en)
g2.set_xscale("symlog", linthresh=100)
g2.set_xticks([0, 50, 100, 300, 1000, 3000, 5000])
g2.set_xticklabels(["0", "50", "100", "300", "1,000", "3,000", "5,000"])
g2.set_xlabel("TWh per year, logarithmic scale above 100")
g2.legend(loc="lower right", fontsize=9)
g2.grid(axis="x", alpha=0.3)
g2.set_title("Where Artesia 4 lacks plants, the freed fossil substations have almost all the room needed", fontsize=11)
fig.savefig("schema_postes_reutilisables_artesia.png", dpi=110)
