import sys
import json
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pathlib import Path

# Accept file path as command-line argument
if len(sys.argv) > 1:
    data_path = sys.argv[1]
else:
    data_path = "/Users/maxim.ziatdinov/Code/SciLink/planning_session_20260319_152853/data/spectrum_T25.0_pH4.0.csv"

try:
    # Read spectrum data
    df = pd.read_csv(data_path)
    
    # Load sidecar conditions dynamically
    sidecar_path = Path(data_path).with_suffix('.json')
    sidecar_conditions = {}
    if sidecar_path.exists():
        with open(sidecar_path) as f:
            sidecar_conditions = json.load(f)
    
    # Extract wavelength and absorbance
    wavelength = df['wavelength_nm'].values
    absorbance = df['absorbance'].values
    
    # Compute targets
    # 1. Peak absorbance (maximum absorbance value)
    peak_idx = np.argmax(absorbance)
    peak_absorbance = float(absorbance[peak_idx])
    
    # 2. Peak wavelength (wavelength at maximum absorbance)
    peak_wavelength_nm = float(wavelength[peak_idx])
    
    # 3. Integrated absorbance (area under curve via trapezoidal rule)
    # Sort by wavelength to ensure proper integration
    sort_idx = np.argsort(wavelength)
    wavelength_sorted = wavelength[sort_idx]
    absorbance_sorted = absorbance[sort_idx]
    integrated_absorbance = float(np.trapezoid(absorbance_sorted, wavelength_sorted))
    
    # Build metrics: sidecar conditions + computed targets
    metrics = {
        **sidecar_conditions,
        "peak_absorbance": round(peak_absorbance, 6),
        "peak_wavelength_nm": round(peak_wavelength_nm, 2),
        "integrated_absorbance": round(integrated_absorbance, 4)
    }
    
    # Generate plot
    output_dir = Path("/Users/maxim.ziatdinov/Code/SciLink/planning_session_20260319_152853/scalarizer_outputs")
    output_dir.mkdir(parents=True, exist_ok=True)
    plot_path = output_dir / f"debug_{Path(data_path).stem}.png"
    
    fig, ax = plt.subplots(1, 1, figsize=(10, 5))
    
    # Plot spectrum
    ax.plot(wavelength_sorted, absorbance_sorted, 'b-', linewidth=0.8, label='Spectrum')
    
    # Shade integrated area
    ax.fill_between(wavelength_sorted, 0, absorbance_sorted, alpha=0.2, color='steelblue',
                     label=f'Integrated area = {integrated_absorbance:.4f}')
    
    # Mark peak
    ax.plot(peak_wavelength_nm, peak_absorbance, 'rv', markersize=12,
            label=f'Peak: {peak_absorbance:.4f} @ {peak_wavelength_nm:.1f} nm')
    ax.axvline(peak_wavelength_nm, color='r', linestyle='--', alpha=0.4)
    
    # Labels and title
    cond_str = ', '.join([f"{k}={v}" for k, v in sidecar_conditions.items()])
    ax.set_title(f'UV-Vis Spectrum ({cond_str})\n'
                 f'Peak={peak_absorbance:.4f} @ {peak_wavelength_nm:.1f} nm, '
                 f'Integrated={integrated_absorbance:.4f}', fontsize=11)
    ax.set_xlabel('Wavelength (nm)')
    ax.set_ylabel('Absorbance')
    ax.legend(loc='best', fontsize=9)
    ax.set_xlim(wavelength_sorted[0], wavelength_sorted[-1])
    ax.set_ylim(bottom=0)
    
    plt.tight_layout()
    plt.savefig(str(plot_path), dpi=150)
    plt.close()
    
    # Output JSON
    result = {
        "metrics": metrics,
        "plot_path": str(plot_path)
    }
    print(json.dumps(result))

except Exception as e:
    result = {
        "metrics": None,
        "plot_path": None,
        "error": str(e)
    }
    print(json.dumps(result))
