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 ".."
SORTIE = sys.argv[2] if len(sys.argv) > 2 else "."
s = pd.read_csv(f"{D}/sources_karstiques_wokas.csv")
g4 = pd.read_csv(f"{D}/gold4_sources_artesia_5.csv")
p = pd.read_csv(f"{D}/plan_mondial_artesia_5_v1_sites.csv")
fig, g = plt.subplots(figsize=(16, 8.5))
la, lo = np.meshgrid(np.arange(-60, 85, 0.5), np.arange(-180, 180, 0.5), indexing="ij")
g.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")
q = p[p.type.isin(["crete", "soleil", "mixte", "poste"])]
g.scatter(q.lon, q.lat, s=1.5, color="#2e8b57", alpha=0.25, label="V14 plants of the Artesia 5 plan")
a = s[s.debit_moyen_m3s < 1]
g.scatter(a.Longitude, a.Latitude, s=8, color="#95a5a6", label=f"WoKaS database springs below 1 m³/s: {len(a)}")
b = s[s.debit_moyen_m3s >= 1]
g.scatter(b.Longitude, b.Latitude, s=14, color="#2874a6", label=f"Springs of 1 m³/s and more: {len(b)}")
u = g4[g4.gwh >= 5].merge(s[["Name", "Longitude", "Latitude"]], left_on="source", right_on="Name")
g.scatter(u.Longitude, u.Latitude, s=60, facecolors="none", edgecolors="#c0392b", lw=2, label=f"Springs useful to a plan plant (5 GWh and more): {len(u)}")
x0, y0 = -42, -52
k = 2000 / 111.32
g.plot([x0, x0 + k], [y0, y0], color="black", lw=3)
g.plot([x0, x0], [y0 - 1, y0 + 1], color="black", lw=2)
g.plot([x0 + k, x0 + k], [y0 - 1, y0 + 1], color="black", lw=2)
g.text(x0 + k / 2, y0 + 2, "2,000 km (at the equator)", ha="center", fontsize=9)
g.set_xlim(-180, 180)
g.set_ylim(-60, 85)
g.set_xticks([])
g.set_yticks([])
g.legend(loc="lower left", fontsize=9, markerscale=1.5, framealpha=0.9)
g.set_title("The large karst springs of the WoKaS world database and the Artesia 5 V14 plants within 25 km", fontsize=12)
fig.tight_layout()
fig.savefig(f"{SORTIE}/carte_gold4_sources.png", dpi=110)
