"""Phaxor — Vibration Analysis Engine (Python port)"""
import math

def solve_vibration(inputs: dict) -> dict | None:
    """Vibration Analysis Calculator for SDOF systems."""
    mass = float(inputs.get('mass', 0))
    stiffness = float(inputs.get('stiffness', 0))
    damping = float(inputs.get('damping', 0))
    force_amp = float(inputs.get('forceAmp', 0))
    force_freq = float(inputs.get('forceFreq', 0))
    x0 = float(inputs.get('x0', 0))

    if mass <= 0 or stiffness < 0:
        return None

    wn = math.sqrt(stiffness / mass)
    cc = 2 * mass * wn # Critical damping
    zeta = damping / cc if cc > 0 else 0

    wd = 0
    if zeta < 1:
        wd = wn * math.sqrt(1 - zeta * zeta)
    else:
        wd = 0 # Overdamped/critical

    period = (2 * math.pi) / wd if wd > 0 else float('inf')

    # Frequency ratio
    omega = 2 * math.pi * force_freq
    r = omega / wn if wn > 0 else 0

    # Magnification factor
    denom = math.sqrt((1 - r * r) ** 2 + (2 * zeta * r) ** 2)
    m_factor = 1 / denom if denom > 0 else 0

    # Steady-state amplitude
    x_static = (force_amp / stiffness) * 1000 if stiffness > 0 else 0 # mm
    peak_amp = x_static * m_factor

    # Phase angle (degrees)
    phi = math.atan2(2 * zeta * r, 1 - r * r) * (180 / math.pi)

    # Transmissibility
    tr = 0
    if denom > 0:
        num = math.sqrt(1 + (2 * zeta * r) ** 2)
        tr = num / denom
    
    system_type = 'Underdamped'
    if abs(zeta - 1) < 0.001:
        system_type = 'Critically Damped'
    elif zeta > 1:
        system_type = 'Overdamped'

    return {
        'naturalFreq': float(f"{wn:.4f}"),
        'naturalFreqHz': float(f"{wn / (2 * math.pi):.4f}"),
        'dampedFreq': float(f"{wd:.4f}"),
        'dampedFreqHz': float(f"{wd / (2 * math.pi):.4f}") if wd > 0 else 0,
        'dampingRatio': float(f"{zeta:.4f}"),
        'criticalDamping': float(f"{cc:.2f}"),
        'period': float(f"{period:.4f}") if period != float('inf') else 0,
        'peakAmplitude': float(f"{peak_amp:.4f}"),
        'magnificationFactor': float(f"{m_factor:.4f}"),
        'phaseAngle': float(f"{phi:.2f}"),
        'transmissibility': float(f"{tr:.4f}"),
        'systemType': system_type
    }
