"""Phaxor — Bearing Life Engine (Python port)"""
import math

RELIABILITY_FACTORS = {
    '90': {'label': '90% (L10)', 'a1': 1.0},
    '95': {'label': '95% (L5)', 'a1': 0.62},
    '96': {'label': '96% (L4)', 'a1': 0.53},
    '97': {'label': '97% (L3)', 'a1': 0.44},
    '98': {'label': '98% (L2)', 'a1': 0.33},
    '99': {'label': '99% (L1)', 'a1': 0.21},
}

def solve_bearing_life(inputs: dict) -> dict | None:
    """Bearing Life Calculator (ISO 281)."""
    c = float(inputs.get('C', 0))
    radial_load = float(inputs.get('radialLoad', 0))
    axial_load = float(inputs.get('axialLoad', 0))
    rpm = float(inputs.get('rpm', 0))
    type_ = inputs.get('type', 'ball')
    reliability = inputs.get('reliability', '90')
    bore = float(inputs.get('bore', 0))
    x = float(inputs.get('X', 1))
    y = float(inputs.get('Y', 0))

    if c <= 0 or rpm < 0:
        return None

    # Equivalent load: P = X·Fr + Y·Fa
    p_eq = abs(x * radial_load + y * axial_load)

    # Life exponent: 3 for ball, 10/3 for roller
    p = 3 if type_ == 'ball' else 10 / 3

    # L10 in millions of revolutions
    l10_revs = math.pow(c / p_eq, p) if p_eq > 0 else float('inf')

    # L10 in hours
    l10_hours = (l10_revs * 1e6) / (60 * rpm) if rpm > 0 else float('inf')

    # Adjusted life with reliability factor
    a1 = RELIABILITY_FACTORS.get(reliability, {'a1': 1.0})['a1']
    l10_adjusted = l10_hours * a1

    load_ratio = c / p_eq if p_eq > 0 else float('inf')
    speed_factor = bore * rpm # DN value

    return {
        'L10revs': float(f"{l10_revs:.1f}"),
        'L10hours': float(f"{l10_hours:.0f}"),
        'L10adjusted': float(f"{l10_adjusted:.0f}"),
        'equivalentLoad': float(f"{p_eq:.1f}"),
        'loadRatio': float(f"{load_ratio:.2f}"),
        'speedFactor': float(f"{speed_factor:.0f}"),
        'safe': l10_hours >= 5000
    }
