"""MIT. Standard Matplotlib figures from the independently computed references."""
import argparse
import csv
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from analytic_cloud import uniform_sphere_intensity,two_channel_filter

def finish(figure,path):
    figure.tight_layout();figure.savefig(path,metadata={'Date':None,'Creator':'Sandbox Physics independent analytic references'});plt.close(figure)

def main():
    parser=argparse.ArgumentParser();parser.add_argument('--results',type=Path,default=Path('results'));parser.add_argument('--output',type=Path,default=Path('results/figures'));args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
    plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'svg.fonttype':'path','svg.hashsalt':'ac34-independent-v1','axes.spines.top':False,'axes.spines.right':False})
    for mobile in [False,True]:render(args,mobile)

def render(args,mobile):
    with (args.results/'ideal-history.csv').open() as stream:rows=list(csv.DictReader(stream))
    time=np.array([float(row['tau']) for row in rows]);radius=np.array([float(row['ion_count_radius_over_Rs']) for row in rows]);line=np.array([float(row['line_over_steady']) for row in rows])
    figure,axes=plt.subplots(2,1,figsize=(3.6,4.8) if mobile else (7,5),sharex=True)
    axes[0].plot(time,radius,color='#168eaa',lw=2,label='Ion-count-equivalent radius');axes[0].set_ylabel(r'$R_N/R_S$');axes[0].legend(frameon=False,loc='lower right')
    axes[1].plot(time,line,color='#cb4e4e',lw=2,label='Fixed-yield hydrogen line');axes[1].set_ylabel(r'$L/L_{\rm steady}$');axes[1].set_xlabel(r'Time $t/t_{\rm rec}$');axes[1].legend(frameon=False)
    for axis in axes:axis.axvspan(2,3,color='#dce5eb',alpha=.65);axis.set_xlim(0,3);axis.grid(alpha=.2)
    axes[0].set_title('Own fixed-gas ideal reference' if mobile else 'Own ideal fixed-gas reference; source off after two recombination times')
    finish(figure,args.output/('history-mobile.svg' if mobile else 'history.svg'))
    b=np.linspace(0,1,401);intensity=np.array([uniform_sphere_intensity(float(x),1,2*np.pi) for x in b])
    figure,axes=plt.subplots(2 if mobile else 1,1 if mobile else 2,figsize=(3.6,6) if mobile else (8,3.5),gridspec_kw={} if mobile else {'width_ratios':[1.2,1]})
    axes[0].plot(b,intensity,color='#cb4e4e',lw=2);axes[0].set(xlabel=r'Impact parameter $b/R$',ylabel=r'$I(b)/I(0)$',title='Uniform sphere, optically thin');axes[0].grid(alpha=.2)
    coordinate=np.linspace(-1,1,301);x,y=np.meshgrid(coordinate,coordinate);image=np.sqrt(np.maximum(0,1-x*x-y*y))
    axes[1].imshow(image,origin='lower',extent=[-1,1,-1,1],cmap='magma',vmin=0,vmax=1);axes[1].set(xlabel=r'$x/R$',ylabel=r'$y/R$',title='Same analytic sightline intensity')
    finish(figure,args.output/('projection-mobile.svg' if mobile else 'projection.svg'))
    optical_depth=np.linspace(0,4,201);filtered=[two_channel_filter(float(tau)) for tau in optical_depth]
    figure,axes=plt.subplots(2 if mobile else 1,1 if mobile else 2,figsize=(3.6,6.2) if mobile else (8,3.5))
    axes[0].plot(optical_depth,[row['channels'][0] for row in filtered],color='#c77e25',label='18 eV channel');axes[0].plot(optical_depth,[row['channels'][1] for row in filtered],color='#397ab6',label='36 eV channel');axes[0].plot(optical_depth,[row['surviving_fraction'] for row in filtered],color='#434b51',ls='--',label='Total surviving photons');axes[0].set(xlabel=r'18 eV optical depth',ylabel='Fraction of original photon supply');axes[0].legend(frameon=False,fontsize=8)
    axes[1].plot(optical_depth,[row['hard_fraction'] for row in filtered],color='#397ab6',lw=2);axes[1].set(xlabel='18 eV optical depth',ylabel='Hard share of surviving photons' if mobile else '36 eV share among surviving photons',ylim=(0,1))
    for axis in axes:axis.grid(alpha=.2)
    figure.suptitle('Synthetic two-channel filtering' if mobile else 'Own two-channel filtering illustration; no metal-line prediction')
    finish(figure,args.output/('hardening-mobile.svg' if mobile else 'hardening.svg'))

if __name__=='__main__':main()
