"""Phaxor — Chemical Equilibrium Engine (Python port)"""
import math

R_GAS = 8.314

def solve_chem_equilibrium(inputs: dict) -> dict | None:
    """Chemical Equilibrium Calculator."""
    a = float(inputs.get('a', 0))
    b = float(inputs.get('b', 0))
    c = float(inputs.get('c', 0))
    d = float(inputs.get('d', 0))
    ca0 = float(inputs.get('cA0', 0))
    cb0 = float(inputs.get('cB0', 0))
    keq = float(inputs.get('Keq', 0))
    temp = float(inputs.get('T', 298))
    dh = float(inputs.get('dH', 0))

    if keq <= 0 or ca0 <= 0:
        return None

    max_xi = min(
        (ca0 / a) if a > 0 else 1e9,
        (cb0 / b) if b > 0 else 1e9
    )

    def calc_q(xi):
        ca = max(ca0 - a * xi, 1e-15)
        cb = max(cb0 - b * xi, 1e-15) if b > 0 else 1.0
        cc = max(c * xi, 1e-15)
        cd = max(d * xi, 1e-15) if d > 0 else 1.0
        
        num = pow(cc, c) * (pow(cd, d) if d > 0 else 1.0)
        den = pow(ca, a) * (pow(cb, b) if b > 0 else 1.0)
        return num / den

    # Bisection
    lo = 1e-10
    hi = max_xi * 0.9999
    xi = 0.0

    for _ in range(100):
        mid = (lo + hi) / 2.0
        q = calc_q(mid)
        if q < keq:
            lo = mid
        else:
            hi = mid
        if abs(q - keq) / keq < 1e-6:
            break
            
    xi = (lo + hi) / 2.0

    ca_eq = ca0 - a * xi
    cb_eq = cb0 - b * xi if b > 0 else 0.0
    cc_eq = c * xi
    cd_eq = d * xi if d > 0 else 0.0
    conv_a = (a * xi) / ca0

    delta_g = -R_GAS * temp * math.log(keq)
    
    direction = 'Exothermic (↑T shifts ←)' if dh < 0 else ('Endothermic (↑T shifts →)' if dh > 0 else 'Neutral')

    vant_hoff = []
    t_min = max(200, int(temp - 200))
    t_max = int(temp + 200)
    step_t = max(1, (t_max - t_min) // 20)
    
    for t in range(t_min, t_max + 1, step_t):
        kt = keq * math.exp((-dh / R_GAS) * (1.0/t - 1.0/temp))
        vant_hoff.append({
            'T': t,
            'K': float(f"{kt:.4f}"),
            'lnK': float(f"{math.log(kt):.3f}")
        })

    return {
        'xi': float(f"{xi:.6f}"),
        'cA_eq': float(f"{ca_eq:.4f}"),
        'cB_eq': float(f"{cb_eq:.4f}"),
        'cC_eq': float(f"{cc_eq:.4f}"),
        'cD_eq': float(f"{cd_eq:.4f}"),
        'conversionA': float(f"{conv_a:.4f}"),
        'deltaG': float(f"{delta_g:.2f}"),
        'direction': direction,
        'vantHoffData': vant_hoff
    }
