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

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_20260319_131557/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 wavelength and absorbance
    wavelength = df['wavelength_nm'].values
    absorbance = df['absorbance'].values

    # Calculate peak absorbance and peak wavelength
    peak_idx = np.argmax(absorbance)
    peak_absorbance = float(absorbance[peak_idx])
    peak_wavelength = float(wavelength[peak_idx])

    # Calculate integrated absorbance (area under the curve)
    # 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 + derived values
    metrics = {
        **sidecar_conditions,
        "Peak_Absorbance": peak_absorbance,
        "Peak_Wavelength_nm": peak_wavelength,
        "Integrated_Absorbance": integrated_absorbance
    }

    # Generate plot
    output_dir = Path("/Users/maxim.ziatdinov/Code/SciLink/planning_session_20260319_131557/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))

    # 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='blue',
                     label=f'Integrated Area = {integrated_absorbance:.4f}')

    # Mark peak
    ax.plot(peak_wavelength, peak_absorbance, 'ro', markersize=8, zorder=5,
            label=f'Peak: {peak_absorbance:.4f} @ {peak_wavelength:.1f} nm')
    ax.axvline(peak_wavelength, 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})\nPeak={peak_absorbance:.4f} @ {peak_wavelength:.1f} nm, Area={integrated_absorbance:.4f}",
                 fontsize=10)
    ax.set_xlabel('Wavelength (nm)')
    ax.set_ylabel('Absorbance')
    ax.legend(fontsize=8, loc='best')
    ax.set_xlim(wavelength_sorted[0], wavelength_sorted[-1])
    plt.tight_layout()
    fig.savefig(str(plot_path), dpi=150)
    plt.close(fig)

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

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