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

try:
    # 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_20260306_024930/data/spectrum_T25.0_pH4.0.csv"

    # Read data
    df = pd.read_csv(data_path)

    # Load sidecar JSON 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 columns
    wavelength = df['wavelength_nm'].values
    absorbance = df['absorbance'].values

    # Apply light smoothing to avoid noise spikes being picked as the peak
    # Use Savitzky-Golay filter if enough points, otherwise use raw
    if len(absorbance) >= 11:
        window = min(11, len(absorbance) if len(absorbance) % 2 == 1 else len(absorbance) - 1)
        abs_smooth = savgol_filter(absorbance, window_length=window, polyorder=2)
    else:
        abs_smooth = absorbance.copy()

    # Find peak: index of maximum in smoothed data
    peak_idx = np.argmax(abs_smooth)
    peak_wavelength = float(wavelength[peak_idx])
    # Report the actual (unsmoothed) absorbance at the peak wavelength
    peak_absorbance = float(absorbance[peak_idx])
    # Also get the smoothed value for reference
    peak_abs_smooth = float(abs_smooth[peak_idx])

    # Build metrics: sidecar conditions + derived targets
    metrics = {
        **sidecar_conditions,
        "Peak_Absorbance": round(peak_absorbance, 6),
        "Peak_Wavelength_nm": round(peak_wavelength, 1)
    }

    # --- Plot ---
    output_dir = Path("/Users/maxim.ziatdinov/Code/SciLink/planning_session_20260306_024930/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=(8, 5))
    ax.plot(wavelength, absorbance, color='steelblue', alpha=0.5, linewidth=0.8, label='Raw')
    ax.plot(wavelength, abs_smooth, color='navy', linewidth=1.2, label='Smoothed')
    ax.axvline(peak_wavelength, color='red', linestyle='--', alpha=0.7, label=f'Peak @ {peak_wavelength:.1f} nm')
    ax.plot(peak_wavelength, peak_absorbance, 'ro', markersize=10, zorder=5)
    ax.annotate(f'Max Abs = {peak_absorbance:.4f}\n@ {peak_wavelength:.1f} nm',
                xy=(peak_wavelength, peak_absorbance),
                xytext=(peak_wavelength + 20, peak_absorbance * 0.9),
                arrowprops=dict(arrowstyle='->', color='red'),
                fontsize=10, color='red', fontweight='bold')
    cond_str = ', '.join(f'{k}={v}' for k, v in sidecar_conditions.items())
    ax.set_title(f'UV-Vis Spectrum — Peak Abs={peak_absorbance:.4f} @ {peak_wavelength:.1f} nm\n({cond_str})', fontsize=11)
    ax.set_xlabel('Wavelength (nm)')
    ax.set_ylabel('Absorbance')
    ax.legend(loc='best')
    ax.grid(True, alpha=0.3)
    plt.tight_layout()
    fig.savefig(str(plot_path), dpi=150)
    plt.close(fig)

    # Output
    result = {
        "metrics": metrics,
        "plot_path": str(plot_path)
    }
    print(json.dumps(result))

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