"""Phaxor — Torque & Power Engine (Python port)"""
import math

def solve_torque_power(inputs: dict) -> dict | None:
    """Solve for Torque, Power, or Speed and calculate system stats."""
    mode = inputs.get('mode', 'torque-to-power')
    torque = float(inputs.get('torque', 0))
    rpm = float(inputs.get('rpm', 0))
    power = float(inputs.get('power', 0))
    efficiency = float(inputs.get('efficiency', 90))
    trans_eff = float(inputs.get('transEff', 100))
    voltage = float(inputs.get('voltage', 415))
    pf = float(inputs.get('pf', 0.85))
    phases = int(inputs.get('phases', 3))

    eff = max(0.01, min(100, efficiency)) / 100
    t_eff = max(0.01, min(100, trans_eff)) / 100

    calc_t = torque
    calc_p = power  # kW
    calc_n = rpm

    omega = calc_n * (2 * math.pi) / 60

    if mode == 'torque-to-power':
        calc_p = (calc_t * omega) / 1000
    elif mode == 'power-to-torque':
        if omega > 0:
            calc_t = (calc_p * 1000) / omega
        else:
            calc_t = 0
    elif mode == 'speed-from-power':
        if calc_t > 0:
            omega = (calc_p * 1000) / calc_t
            calc_n = (omega * 60) / (2 * math.pi)
        else:
            calc_n = 0
            omega = 0

    shaft_power = calc_p
    input_power = shaft_power / eff
    final_output_power = shaft_power * t_eff
    total_losses = input_power - final_output_power
    power_hp = shaft_power / 0.746

    p_in_watts = input_power * 1000
    if phases == 3:
        current = p_in_watts / (math.sqrt(3) * voltage * pf)
    else:
        current = p_in_watts / (voltage * pf)

    motor_class = 'Small'
    if shaft_power < 0.75:
        motor_class = 'Fractional HP'
    elif shaft_power < 10:
        motor_class = 'Small Industrial'
    elif shaft_power < 100:
        motor_class = 'Medium Industrial'
    else:
        motor_class = 'Large Industrial'

    return {
        'torque': float(f"{calc_t:.4f}"),
        'rpm': float(f"{calc_n:.2f}"),
        'shaftPower': float(f"{shaft_power:.4f}"),
        'inputPower': float(f"{input_power:.4f}"),
        'outputPower': float(f"{final_output_power:.4f}"),
        'losses': float(f"{total_losses:.4f}"),
        'powerHP': float(f"{power_hp:.4f}"),
        'omega': float(f"{omega:.4f}"),
        'current': float(f"{current:.2f}"),
        'motorClass': motor_class
    }
