"""Phaxor — Gibbs Free Energy Engine (Python port)"""
import math

R_GAS = 8.314

def solve_gibbs(inputs: dict) -> dict | None:
    """Gibbs Free Energy Calculator."""
    dh = float(inputs.get('dH', 0))
    ds = float(inputs.get('dS', 0))
    temp = float(inputs.get('T', 298))

    if temp <= 0:
        return None

    delta_g = dh - temp * ds
    spontaneous = delta_g < 0

    # Keq
    try:
        keq = math.exp(-delta_g / (R_GAS * temp))
    except OverflowError:
        keq = float('inf') if -delta_g / (R_GAS * temp) > 0 else 0.0

    # Tcross
    t_cross = (dh / ds) if ds != 0 else None

    # Plot
    plot_data = []
    for t in range(100, 1501, 50):
        g = dh - t * ds
        plot_data.append({'T': t, 'dG': float(f"{g / 1000.0:.2f}")})

    # Classification
    enthalpy_driven = dh < 0
    entropy_driven = ds > 0
    classification = ""
    if enthalpy_driven and entropy_driven: classification = 'Spontaneous at all T'
    elif not enthalpy_driven and not entropy_driven: classification = 'Non-spontaneous at all T'
    elif enthalpy_driven and not entropy_driven: classification = 'Spontaneous at low T'
    else: classification = 'Spontaneous at high T'

    bar_data = [
        {'name': 'ΔH', 'value': float(f"{dh / 1000.0:.1f}"), 'color': '#22c55e' if dh < 0 else '#ef4444'},
        {'name': '−TΔS', 'value': float(f"{-(temp * ds) / 1000.0:.1f}"), 'color': '#ef4444' if (temp*ds) > 0 else '#22c55e'},
        {'name': 'ΔG', 'value': float(f"{delta_g / 1000.0:.1f}"), 'color': '#22c55e' if delta_g < 0 else '#ef4444'}
    ]

    return {
        'deltaG': float(f"{delta_g:.2f}"),
        'spontaneous': spontaneous,
        'Keq': keq,
        'Tcross': float(f"{t_cross:.2f}") if t_cross is not None else None,
        'classification': classification,
        'plotData': plot_data,
        'barData': bar_data
    }
