"""Phaxor — Packed Bed Engine (Python port)"""
import math

def solve_packed_bed(inputs: dict) -> dict | None:
    """Packed Bed Pressure Drop Calculator (Ergun)."""
    dp = float(inputs.get('dp', 0))
    l_bed = float(inputs.get('L', 0))
    eps = float(inputs.get('eps', 0))
    mu = float(inputs.get('mu', 0))
    rho = float(inputs.get('rho', 0))
    u = float(inputs.get('u', 0))

    if dp <= 0 or l_bed <= 0 or eps <= 0 or eps >= 1 or mu <= 0 or rho <= 0 or u <= 0:
        return None

    term1 = 150.0 * mu * u * pow(1.0 - eps, 2) / (pow(dp, 2) * pow(eps, 3))
    term2 = 1.75 * rho * pow(u, 2) * (1.0 - eps) / (dp * pow(eps, 3))
    
    dp_per_l = term1 + term2
    dp_total = dp_per_l * l_bed
    
    re_p = rho * u * dp / (mu * (1.0 - eps))
    regime = 'Laminar (Re < 10)' if re_p < 10 else ('Turbulent (Re > 1000)' if re_p > 1000 else 'Transition')

    vel_data = []
    max_u = u * 3.0
    step_u = max_u / 20.0
    v = step_u
    while v <= max_u + 1e-9:
        t1 = 150.0 * mu * v * pow(1.0 - eps, 2) / (pow(dp, 2) * pow(eps, 3))
        t2 = 1.75 * rho * pow(v, 2) * (1.0 - eps) / (dp * pow(eps, 3))
        vel_data.append({
            'u': float(f"{v:.3f}"),
            'dP': float(f"{(t1 + t2) * l_bed / 1000.0:.2f}"), # kPa
            'viscous': float(f"{t1 * l_bed / 1000.0:.2f}"),
            'inertial': float(f"{t2 * l_bed / 1000.0:.2f}")
        })
        v += step_u

    eps_data = []
    e = 0.25
    while e <= 0.8:
        t1e = 150.0 * mu * u * pow(1.0 - e, 2) / (pow(dp, 2) * pow(e, 3))
        t2e = 1.75 * rho * pow(u, 2) * (1.0 - e) / (dp * pow(e, 3))
        eps_data.append({
            'eps': float(f"{e:.2f}"),
            'dP': float(f"{(t1e + t2e) * l_bed / 1000.0:.2f}")
        })
        e += 0.05

    return {
        'dP': float(f"{dp_total:.1f}"),
        'dPperL': float(f"{dp_per_l:.1f}"),
        'term1': float(f"{term1:.1f}"),
        'term2': float(f"{term2:.1f}"),
        'Re': float(f"{re_p:.2f}"),
        'regime': regime,
        'velData': vel_data,
        'epsData': eps_data
    }
