"""Phaxor — Stoichiometry Engine (Python port)"""

def solve_stoichiometry(inputs: dict) -> dict | None:
    """Stoichiometry Calculator."""
    reactants = inputs.get('reactants', [])
    products = inputs.get('products', [])

    if not reactants:
        return None
    
    r_a = reactants[0]
    r_a_coeff = float(r_a.get('coeff', 0))
    if r_a_coeff <= 0: return None
    
    n_a = float(r_a.get('moles', 0))

    limiting_name = r_a.get('name', 'Reactant A')
    base_moles = n_a / r_a_coeff
    excess_name = ""
    excess_remaining = 0.0
    is_a_limiting = True

    r_b = None
    if len(reactants) > 1:
        r_b = reactants[1]
        r_b_coeff = float(r_b.get('coeff', 0))
        n_b = float(r_b.get('moles', 0))
        
        if r_b_coeff > 0 and n_b > 0:
            ratio_a = n_a / r_a_coeff
            ratio_b = n_b / r_b_coeff
            
            if ratio_b < ratio_a:
                is_a_limiting = False
                limiting_name = r_b.get('name', 'Reactant B')
                excess_name = r_a.get('name', 'Reactant A')
                base_moles = ratio_b
                used_a = base_moles * r_a_coeff
                excess_remaining = n_a - used_a
            else:
                excess_name = r_b.get('name', 'Reactant B')
                used_b = base_moles * r_b_coeff
                excess_remaining = n_b - used_b

    species_data = []
    total_mass_r = 0.0
    total_mass_p = 0.0

    # R_A
    moles_a_used = base_moles * r_a_coeff
    mass_a_used = moles_a_used * float(r_a.get('molarMass', 1))
    total_mass_r += mass_a_used
    species_data.append({
        'name': r_a.get('name', 'A'),
        'type': 'Reactant',
        'moles': float(f"{moles_a_used:.3f}"),
        'mass': float(f"{mass_a_used:.2f}"),
        'color': '#ef4444'
    })

    # R_B
    if r_b and float(r_b.get('coeff', 0)) > 0:
        moles_b_used = base_moles * float(r_b.get('coeff', 0))
        mass_b_used = moles_b_used * float(r_b.get('molarMass', 1))
        total_mass_r += mass_b_used
        species_data.append({
            'name': r_b.get('name', 'B'),
            'type': 'Reactant',
            'moles': float(f"{moles_b_used:.3f}"),
            'mass': float(f"{mass_b_used:.2f}"),
            'color': '#f59e0b'
        })
    
    # Products
    for p in products:
        coeff = float(p.get('coeff', 0))
        if coeff > 0:
            moles = base_moles * coeff
            mass = moles * float(p.get('molarMass', 1))
            total_mass_p += mass
            species_data.append({
                'name': p.get('name', 'Product'),
                'type': 'Product',
                'moles': float(f"{moles:.3f}"),
                'mass': float(f"{mass:.2f}"),
                'color': '#22c55e'
            })

    return {
        'limitingName': limiting_name,
        'excessName': excess_name,
        'excessRemaining': float(f"{excess_remaining:.3f}"),
        'isALimiting': is_a_limiting,
        'speciesData': species_data,
        'massBalance': {
            'reactants': float(f"{total_mass_r:.2f}"),
            'products': float(f"{total_mass_p:.2f}")
        }
    }
