"""Phaxor — Induction Motor Engine (Python port)"""
import math

def solve_induction_motor(inputs: dict) -> dict | None:
    """Induction Motor Calculator."""
    power_kw = float(inputs.get('powerKW', 0))
    poles = int(inputs.get('poles', 4))
    freq = float(inputs.get('frequency', 50))
    v = float(inputs.get('voltage', 415))
    eff = float(inputs.get('efficiency', 85))
    pf = float(inputs.get('powerFactor', 0.85))
    start_mult = float(inputs.get('startMultiplier', 6))
    slip_percent = inputs.get('slipPercent') # Optional

    if power_kw <= 0 or v <= 0:
        return None

    p = max(2, int(poles))
    eff_val = max(0.1, min(100.0, eff)) / 100.0
    pf = max(0.01, min(1.0, pf))
    ist_mult = max(1.0, start_mult)

    ns = (120 * freq) / p
    
    if slip_percent is not None and float(slip_percent) >= 0:
        slip_val = float(slip_percent) / 100.0
    else:
        slip_val = 0.04
        
    nr = ns * (1 - slip_val)
    slip = slip_val * 100

    p_out = power_kw * 1000.0
    p_in = p_out / eff_val
    total_loss = p_in - p_out

    ifl = p_in / (math.sqrt(3) * v * pf)
    ist = ifl * ist_mult

    # T = P / w. w = 2*pi*Nr/60
    w_r = 2 * math.pi * nr / 60 if nr > 0 else 1e-9
    t_fl = p_out / w_r
    t_st = t_fl * 1.5

    hp = power_kw / 0.746

    return {
        'Ns': float(f"{ns:.0f}"),
        'Nr': float(f"{nr:.0f}"),
        'slip': float(f"{slip:.2f}"),
        'P_in': float(f"{p_in:.2f}"),
        'P_out': float(f"{p_out:.2f}"),
        'Ifl': float(f"{ifl:.2f}"),
        'Ist': float(f"{ist:.2f}"),
        'T_fl': float(f"{t_fl:.2f}"),
        'T_st': float(f"{t_st:.2f}"),
        'HP': float(f"{hp:.2f}"),
        'eff': float(f"{eff:.1f}"),
        'totalLoss': float(f"{total_loss:.2f}")
    }
