"""Phaxor — Rectifier Engine (Python port)"""
import math

def solve_rectifier(inputs: dict) -> dict | None:
    """Rectifier Calculation Engine."""
    r_type = inputs.get('rectifierType', 'full-bridge')
    vac = float(inputs.get('vacRms', 0))
    freq = float(inputs.get('frequency', 50))
    r_load = float(inputs.get('loadResistance', 10))
    v_diode = float(inputs.get('diodeDrop', 0.7))
    filter_c = float(inputs.get('filterCapacitance', 0)) / 1e6 # uF to F

    if vac <= 0 or r_load <= 0:
        return None

    vm = vac * math.sqrt(2)
    f = freq if freq > 0 else 50.0

    vdc = 0.0
    vrms = 0.0
    ripple_freq = 0.0
    total_drop = 0.0
    form_factor = 0.0
    efficiency = 0.0
    piv = 0.0

    if r_type == 'half':
        total_drop = v_diode
        vdc = (vm - total_drop) / math.pi
        vrms = (vm - total_drop) / 2.0
        ripple_freq = f
        form_factor = math.pi / 2.0
        efficiency = 40.6
        piv = vm
    elif r_type == 'full-center':
        total_drop = v_diode
        vdc = (2 * (vm - total_drop)) / math.pi
        vrms = (vm - total_drop) / math.sqrt(2)
        ripple_freq = 2 * f
        form_factor = 1.11
        efficiency = 81.2
        piv = 2 * vm
    elif r_type == 'full-bridge':
        total_drop = 2 * v_diode
        vdc = (2 * (vm - total_drop)) / math.pi
        vrms = (vm - total_drop) / math.sqrt(2)
        ripple_freq = 2 * f
        form_factor = 1.11
        efficiency = 81.2
        piv = vm
    elif r_type == 'three-phase':
        total_drop = 2 * v_diode
        # Replicating UI formula exactly
        vdc = (3 * math.sqrt(6) * (vm - total_drop)) / (2 * math.pi * math.sqrt(3))
        vrms = vdc * 1.001
        ripple_freq = 6 * f
        form_factor = 1.001
        efficiency = 96.0
        piv = vm * math.sqrt(3)
    else:
        return None

    # Filter Logic
    if filter_c > 0:
        # UI logic: Vdc / (2 * rippleFreq * rl * C)
        ripple_v = vdc / (2 * ripple_freq * r_load * filter_c)
        vdc_filtered = vm - total_drop - (ripple_v / 2.0)
    else:
        ripple_v = vdc * 0.5
        vdc_filtered = vdc

    if vdc_filtered < 0:
        vdc_filtered = 0

    ripple_pct = (ripple_v / max(vdc, 0.01)) * 100.0
    idc = vdc_filtered / r_load
    pdc = vdc_filtered * idc

    return {
        'Vm': float(f"{vm:.2f}"),
        'Vdc': float(f"{vdc:.2f}"),
        'Vdc_filtered': float(f"{vdc_filtered:.2f}"),
        'Vrms': float(f"{vrms:.2f}"),
        'Idc': float(f"{idc:.2f}"),
        'Pdc': float(f"{pdc:.2f}"),
        'rippleVoltage': float(f"{ripple_v:.2f}"),
        'rippleFactorPct': float(f"{ripple_pct:.2f}"),
        'rippleFreq': float(f"{ripple_freq:.2f}"),
        'formFactor': float(f"{form_factor:.3f}"),
        'efficiency': float(f"{efficiency:.2f}"),
        'piv': float(f"{piv:.2f}"),
        'diodeDropTotal': float(f"{total_drop:.2f}")
    }
