"""Plot only retained M02 error magnitudes; no new numerical solves."""
from pathlib import Path
import argparse,csv,hashlib,json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter

def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--results',type=Path,required=True);parser.add_argument('--output',type=Path,required=True)
    args=parser.parse_args();output=args.output
    if output.exists():raise FileExistsError('Fresh figure output required')
    summary_path=args.results/'M02_summary.json';before=sha(summary_path)
    summary=json.loads(summary_path.read_text());output.mkdir(parents=True)
    plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,'axes.spines.right':False,'savefig.facecolor':'white'})
    fig,axes=plt.subplots(2,3,figsize=(16,9.8));colors=['#31688e','#e68226','#20866e'];data=[]
    validmesh=[r for r in summary['mesh_comparisons'] if r['status']=='computed']
    ax=axes[0,0]
    for j,row in enumerate(validmesh):
        values=100*np.abs(row['spectrum']['first6_frequency_signed_relative'])
        label=f"n{row['coarser_n']} to n{row['finer_n']}"
        ax.plot(np.arange(1,7),values,'o-',label=label,color=colors[j])
        data += [{'category':'mesh_first6_frequency','mesh_pair':label,'cutoff':144,'frequency_hz':'','index':i+1,'relative_error':float(v/100)} for i,v in enumerate(values)]
    ax.axhline(2,color='#a71f32',ls='--',label='2% screen');ax.set(title='First six sorted frequencies',xlabel='Sorted frequency index',ylabel='Absolute mesh change (%)');ax.legend(fontsize=8)
    ax=axes[0,1];x=np.arange(3)
    for j,row in enumerate(summary['modal_truncation_by_mesh']):
        values=[100*c['complex_compliance_band_relative_error'] for c in row['comparisons']]
        ax.bar(x+(j-1)*.24,values,.24,label=f"n{row['n']}",color=colors[j])
        data += [{'category':'modal_cutoff','mesh_pair':row['n'],'cutoff':f"{c['coarser_modes']}-{c['finer_modes']}",'frequency_hz':'','index':'','relative_error':c['complex_compliance_band_relative_error']} for c in row['comparisons']]
    ax.axhline(5,color='#a71f32',ls='--');ax.set_xticks(x,['24 to 48','48 to 96','96 to 144']);ax.set(title='Retained-mode change across 161 points',ylabel='Maximum complex compliance change (%)');ax.legend(fontsize=8)
    ax=axes[0,2];x=np.arange(len(validmesh))
    for j,cutoff in enumerate([48,96,144]):
        values=[100*r['whole_band_fixed_cutoff_comparisons'][j]['error'] for r in validmesh]
        ax.bar(x+(j-1)*.24,values,.24,color=colors[j],label=f'{cutoff} modes')
        data += [{'category':'mesh_fixed_cutoff_band','mesh_pair':f"{r['coarser_n']}-{r['finer_n']}",'cutoff':cutoff,'frequency_hz':'','index':'','relative_error':r['whole_band_fixed_cutoff_comparisons'][j]['error']} for r in validmesh]
    ax.axhline(5,color='#a71f32',ls='--');ax.set_xticks(x,[f"n{r['coarser_n']} to n{r['finer_n']}" for r in validmesh]);ax.set(title='Fixed-cutoff whole-band mesh change',ylabel='Maximum complex compliance change (%)');ax.legend(fontsize=8)
    for ax,n in zip(axes[1],[8,10,12]):
        rows=sorted([r for r in summary['direct_vs_modal'] if r['n']==n],key=lambda r:r['frequency_hz'])
        for j,cutoff in enumerate([48,96,144]):
            frequency=[r['frequency_hz']/1000 for r in rows];values=[100*r['comparisons'][j]['mass_norm_relative_error'] for r in rows]
            ax.plot(frequency,values,'o-',color=colors[j],label=f'{cutoff} modes',lw=1.4,ms=4)
            data += [{'category':'direct_mass_norm','mesh_pair':n,'cutoff':cutoff,'frequency_hz':r['frequency_hz'],'index':'','relative_error':r['comparisons'][j]['mass_norm_relative_error']} for r in rows]
        ax.axhline(5,color='#a71f32',ls='--',label='5% screen');ax.set_xscale('log');ax.set_yscale('log')
        ax.set(title=f'n{n}: modal versus same-mesh direct solution',xlabel='Frequency (kHz)',ylabel='Displacement mass-norm error (%)');ax.legend(fontsize=8)
        ax.set_xticks([20,50,100,200],['20','50','100','200'])
        ax.xaxis.set_minor_formatter(NullFormatter())
    for ax in axes.flat:ax.grid(axis='y',alpha=.18)
    fig.suptitle('M02 | More resolution, with remaining error visible',fontsize=19,x=.04,ha='left',y=.987)
    fig.text(.04,.938,'20 mm steel cube · 1 N peak top traction · fixed bottom · assumed Rayleigh damping · zero physical trials',fontsize=11,color='#344050')
    fig.text(.04,.038,'Whole-band metric uses the original 1%-of-peak denominator floor. Fixed-cutoff mesh changes still contain modal error.\nDirect references cover 12 fixed frequencies, not a continuous-frequency or measured-specimen validation. Dashed lines retain the frozen criteria.',fontsize=9,color='#344050')
    fig.tight_layout(rect=[.025,.085,.985,.92],h_pad=2.5,w_pad=2.3)
    for ext in ['png','svg']:fig.savefig(output/f'M02_accuracy.{ext}',dpi=150)
    plt.close(fig)
    with (output/'M02_figure_data.csv').open('w',newline='',encoding='utf-8') as stream:
        writer=csv.DictWriter(stream,fieldnames=['category','mesh_pair','cutoff','frequency_hz','index','relative_error']);writer.writeheader();writer.writerows(data)
    if sha(summary_path)!=before:raise RuntimeError('Input summary changed during plotting')
    manifest={'scope':'Post-run figure generation only; no FEM solve','source_path':'postprocessing/make_figures.py','source_sha256':sha(__file__),
        'input_summary_sha256':before,'source_input_unchanged':True,'numpy_version':np.__version__,'matplotlib_version':matplotlib.__version__,
        'files':{p.name:{'bytes':p.stat().st_size,'sha256':sha(p)} for p in output.iterdir() if p.is_file()}}
    (output/'FIGURE-MANIFEST.json').write_text(json.dumps(manifest,indent=2)+'\n');print(json.dumps(manifest))
if __name__=='__main__':main()
