"""Phaxor — Pump Power Engine (Python port)"""
import math

def solve_pump_power(inputs: dict) -> dict | None:
    """Pump Power and NPSH Calculator."""
    flow_rate = float(inputs.get('flowRate', 300))
    static_head = float(inputs.get('staticHead', 15))
    friction_head = float(inputs.get('frictionHead', 5))
    pressure_head = float(inputs.get('pressureHead', 0))
    pipe_dia = float(inputs.get('pipeDia', 75))
    fluid_density = float(inputs.get('fluidDensity', 998))
    pump_eff = float(inputs.get('pumpEff', 0.75))
    motor_eff = float(inputs.get('motorEff', 0.92))
    rpm = float(inputs.get('rpm', 1450))
    atm_p = float(inputs.get('atmosphericP', 101.325))
    vap_p = float(inputs.get('vaporP', 2.34))
    suction_head = float(inputs.get('suctionHead', 3))
    suction_friction = float(inputs.get('suctionFriction', 0.5))

    if flow_rate < 0 or pipe_dia <= 0 or fluid_density <= 0:
        return None

    g = 9.81
    q = flow_rate / 60000  # m³/s
    d = pipe_dia / 1000    # m
    area = math.pi * d * d / 4
    v = q / area if area > 0 else 0

    # Velocity Head
    vel_head = (v * v) / (2 * g)

    # Total Head
    total_head = static_head + friction_head + pressure_head + vel_head

    # Hydraulic Power: Ph = rho * g * Q * H
    ph = fluid_density * g * q * total_head

    # Shaft Power
    ps = ph / pump_eff if pump_eff > 0 else ph

    # Motor Power
    pm = ps / motor_eff if motor_eff > 0 else ps

    # NPSH Available
    head_atm = (atm_p * 1000) / (fluid_density * g)
    head_vap = (vap_p * 1000) / (fluid_density * g)
    npsha = head_atm + suction_head - suction_friction - head_vap

    # Specific Speed (Metric rpm, m3/s, m)
    # Ns = N * sqrt(Q) / H^0.75
    h_eff = total_head if total_head > 0 else 1
    ns = rpm * math.sqrt(q) / math.pow(h_eff, 0.75)

    # Pump Type
    pump_type = 'Centrifugal (Radial)'
    if ns < 10:
        pump_type = 'Positive Displacement / Radial'
    elif ns < 80:
        pump_type = 'Centrifugal (Radial)'
    elif ns < 160:
        pump_type = 'Mixed Flow'
    else:
        pump_type = 'Axial Flow'

    # Reynolds
    re = (fluid_density * v * d) / 0.001

    return {
        'hydraulicPower': float(f"{ph:.2f}"),
        'shaftPower': float(f"{ps:.2f}"),
        'motorPower': float(f"{pm:.2f}"),
        'totalHead': float(f"{total_head:.2f}"),
        'NPSHav': float(f"{npsha:.2f}"),
        'velocity': float(f"{v:.2f}"),
        'reynolds': float(f"{re:.0f}"),
        'specificSpeed': float(f"{ns:.2f}"),
        'pumpType': pump_type
    }
