import sys
import pandas as pd
import pycountry
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 "."
P=pd.read_csv(f"{D}/prix_centrales_pays.csv",keep_default_na=False).set_index("iso")
PN=pd.read_csv(f"{SORTIE}/prix_centrales_pays.csv",keep_default_na=False).set_index("iso").country.to_dict()
s=pd.read_csv(f"{D}/plan_mondial_artesia_5_v1_sites.csv",keep_default_na=False)
def i3(c):
    p=pycountry.countries.get(alpha_2=c)
    return p.alpha_3 if p else c
s["iso3"]=[i3(c) for c in s.pays]
s["m"]=s.k*s.pris
top=[c for c in s.groupby("iso3").m.sum().sort_values(ascending=False).index if c in P.index][:30]
fig,g=plt.subplots(figsize=(12,11))
y=list(range(len(top)))[::-1]
a=[P.loc[c,"v14_soleil"] for c in top]
b=[P.loc[c,"v14_crete"] for c in top]
g.barh([v+0.2 for v in y],a,height=0.4,color="#d4a017",label="V14 Soleil (trackers and reservoirs)")
g.barh([v-0.2 for v in y],b,height=0.4,color="#2166ac",label="Ridge V14 (wind turbines and reservoirs)")
for v,c,x1,x2 in zip(y,top,a,b):
    g.text(max(x1,x2)+0.02,v,f"{465*x1:.0f} M€ / {364*x2:.0f} M€",va="center",fontsize=8)
g.axvline(1.0,color="black",ls="--",lw=1)
g.text(1.01,len(top)-0.3,"Dashes: French series price used so far",fontsize=8)
g.set_yticks(y)
g.set_yticklabels([PN[c] for c in top])
g.set_xlim(0,1.75)
g.set_xlabel("Price of a plant in the country, France = 1 (labels: price of a V14 Soleil / of a ridge V14)")
g.set_title("The price of the plan's two main plants in the 30 countries where Artesia 5 builds the most of them")
g.legend(loc="lower right",fontsize=9)
g.grid(axis="x",alpha=0.3)
fig.tight_layout()
fig.savefig(f"{SORTIE}/schema_prix_centrales_pays.png",dpi=110)
