"""Run manually AFTER prepare. No network requests and no publication."""
import hashlib,json,sys
from pathlib import Path
import lasio,numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

work=Path(sys.argv[1]);l=lasio.read(work/'input.las',null_policy='strict')
p=json.loads((work/'run.json').read_text())['config']['parameters']
assert l.curves[0].unit.upper()=='M', 'Review the depth unit'
for key,unit in [('DTCO','us/ft'),('DTSM','us/ft'),('RHOB','g/cm3')]:
    assert l.curves[key].unit==unit, f'Review {key} units before calculating'
values={k:l[k].copy() for k in ['DTCO','DTSM','RHOB']}
for key,indices in p['rejected_rows'].items():
    if key not in values:raise ValueError('Unknown correction curve')
    if len(indices)!=len(set(indices)) or any(type(i)!=int or not 0<=i<len(l.index) for i in indices):raise ValueError('Invalid row indices')
    if indices and not p['reason'].strip():raise ValueError('Document your reason')
    values[key][indices]=np.nan
vp=np.full(len(l.index),np.nan);vs=vp.copy()
np.divide(304800.,values['DTCO'],out=vp,where=np.isfinite(values['DTCO'])&(values['DTCO']>0))
np.divide(304800.,values['DTSM'],out=vs,where=np.isfinite(values['DTSM'])&(values['DTSM']>0))
rho=values['RHOB'];rho[~np.isfinite(rho)|(rho<=0)]=np.nan
channels=[('VP_QC','m/s',vp),('VS_QC','m/s',vs),('RHOB_QC','g/cm3',rho)]
curves=[{'mnemonic':name,'unit':unit,'description':'Alice declared QAQC '+name,'values':[float(x) if np.isfinite(x) else None for x in a]} for name,unit,a in channels]
with (work/'curves.json').open('x') as f:json.dump(curves,f,allow_nan=False)
fig,axes=plt.subplots(1,3,figsize=(10,9),sharey=True)
for ax,(name,unit,a) in zip(axes,channels):
    ax.plot(a,l.index,linewidth=.7);ax.set_xlabel(name+' ('+unit+')');ax.grid(True)
axes[0].set_ylabel('Source depth (m; no TVD conversion)');axes[0].set_ylim(p['plot_stop'],p['plot_start']);fig.tight_layout();fig.savefig(work/'alice-review.png',dpi=130)
print('Local output ready for review. Nothing published. Non-missing:',{n:int(np.isfinite(a).sum()) for n,u,a in channels})
