"""Phaxor — Short Circuit Engine (Python port)"""
import math

def solve_short_circuit(inputs: dict) -> dict | None:
    """Short Circuit Fault Calculator."""
    s = float(inputs.get('sourceRating', 0))
    v = float(inputs.get('voltage', 0))
    z_pct = float(inputs.get('impedancePercent', 0))
    xr = float(inputs.get('xrRatio', 6))
    rc = float(inputs.get('cableR', 0))
    xc = float(inputs.get('cableX', 0))
    fault_type = inputs.get('faultType', '3ph')

    if s <= 0 or v <= 0 or z_pct <= 0:
        return None

    ifl = s / (math.sqrt(3) * v)
    z_base = (v * v) / s

    # Transformer Z in Ohms
    z_t = (z_pct / 100.0) * z_base
    phi = math.atan(xr)
    r_t = z_t * math.cos(phi)
    x_t = z_t * math.sin(phi)

    # Total Z
    r_total = r_t + rc
    x_total = x_t + xc
    z_total = math.sqrt(r_total * r_total + x_total * x_total)

    if z_total <= 0: return None

    # 3-phase symmetrical
    isc_3ph = v / (math.sqrt(3) * z_total)

    # Peak
    peak_factor = 1.0 + math.exp(-math.pi / xr)
    i_peak = isc_3ph * math.sqrt(2) * peak_factor

    # Faults
    isc_slg = isc_3ph * 1.0
    isc_ll = isc_3ph * (math.sqrt(3) / 2.0)
    isc_llg = isc_3ph * 1.05

    isc_selected = isc_3ph
    if fault_type == 'slg': isc_selected = isc_slg
    elif fault_type == 'll': isc_selected = isc_ll
    elif fault_type == 'llg': isc_selected = isc_llg

    mva_sc = (math.sqrt(3) * v * isc_3ph) / 1e6

    return {
        'Ifl': float(f"{ifl:.2f}"),
        'Z_total': float(f"{z_total:.5f}"),
        'R_total': float(f"{r_total:.5f}"),
        'X_total': float(f"{x_total:.5f}"),
        'Isc_3ph': float(f"{isc_3ph:.2f}"),
        'Isc_slg': float(f"{isc_slg:.2f}"),
        'Isc_ll': float(f"{isc_ll:.2f}"),
        'Isc_llg': float(f"{isc_llg:.2f}"),
        'Ipeak': float(f"{i_peak:.2f}"),
        'MVAsc': float(f"{mva_sc:.2f}"),
        'Isc_selected': float(f"{isc_selected:.2f}")
    }
