"""Phaxor — Impedance Engine (Python port)"""
import math
import cmath

def solve_impedance(inputs: dict) -> dict | None:
    """Impedance Calculator (RLC Series/Parallel)."""
    r = float(inputs.get('R', 0))
    l_mH = float(inputs.get('L', 0))
    c_uF = float(inputs.get('C', 0))
    freq = float(inputs.get('frequency', 0))
    circuit_type = inputs.get('circuitType', 'series')

    if freq <= 0:
        return None

    # Convert units
    l_h = l_mH / 1000.0 if l_mH > 0 else 0
    c_f = c_uF / 1000000.0 if c_uF > 0 else 0

    omega = 2 * math.pi * freq
    xl = omega * l_h
    xc = 1.0 / (omega * c_f) if c_f > 0 else 0.0

    z_complex = 0j

    if circuit_type == 'series':
        # Z = R + j(XL - XC)
        z_real = r
        z_imag = xl - xc
        z_complex = complex(z_real, z_imag)
    else:
        # Parallel
        # Y = G + j(BC - BL)
        # G = 1/R
        # BC = 1/XC = wC
        # BL = 1/XL = 1/wL
        
        g = 1.0 / r if r > 0 else 0
        bc = 1.0 / xc if xc > 0 else 0  # +j part of Y
        bl = 1.0 / xl if xl > 0 else 0  # -j part of Y (magnitude of susceptance)
        
        y_real = g
        y_imag = bc - bl # Net susceptance B
        
        y_complex = complex(y_real, y_imag)
        
        if abs(y_complex) > 0:
            z_complex = 1.0 / y_complex
        else:
            z_complex = complex(float('inf'), 0) # Infinite impedance (open circuit or perfect resonance)

    z_mag = abs(z_complex)
    phi = cmath.phase(z_complex)
    
    pf = math.cos(phi)
    z_real = z_complex.real
    z_imag = z_complex.imag

    nature = 'Resistive'
    if z_imag > 0.01:
        nature = 'Inductive'
    elif z_imag < -0.01:
        nature = 'Capacitive'

    # Resonant Frequency
    f_res = (1.0 / (2 * math.pi * math.sqrt(l_h * c_f))) if (l_h > 0 and c_f > 0) else 0.0

    return {
        'R': r,
        'XL': float(f"{xl:.2f}"),
        'XC': float(f"{xc:.2f}"),
        'Z': float(f"{z_mag:.2f}"),
        'phi': float(f"{phi:.3f}"),
        'Zreal': float(f"{z_real:.2f}"),
        'Zimag': float(f"{z_imag:.2f}"),
        'pf': float(f"{pf:.3f}"),
        'nature': nature,
        'fRes': float(f"{f_res:.1f}")
    }
