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

def solve_earthing(inputs: dict) -> dict | None:
    """Earthing / Grounding Calculator."""
    rho = float(inputs.get('resistivity', 0))
    e_type = inputs.get('electrodeType', 'rod')
    rod_l = float(inputs.get('rodLength', 3))
    rod_d = float(inputs.get('rodDiameter', 16))
    plate_w = float(inputs.get('plateWidth', 0.6))
    plate_h = float(inputs.get('plateHeight', 0.6))
    strip_l = float(inputs.get('stripLength', 30))
    n_electrodes = int(inputs.get('numElectrodes', 1))
    target_r = float(inputs.get('targetResistance', 5))

    if rho <= 0:
        return None

    target = max(0.1, target_r)
    n = max(1, n_electrodes)

    r_single = 0.0
    if e_type == 'rod':
        L = max(0.1, rod_l)
        d = max(0.1, rod_d) / 1000.0
        r_single = (rho / (2 * math.pi * L)) * math.log(4 * L / d)
    elif e_type == 'plate':
        w = max(0.1, plate_w)
        h = max(0.1, plate_h)
        area = w * h
        r_single = rho / (4 * math.sqrt(area / math.pi))
    else: # strip
        L = max(0.1, strip_l)
        d = 0.012
        r_single = (rho / (math.pi * L)) * math.log(2 * L * L / (d * 0.5))

    # K Factor
    if n == 1:
        k = 1.0
    elif n == 2:
        k = 1.16
    elif n == 3:
        k = 1.29
    elif n == 4:
        k = 1.36
    else:
        k = 1.4 + 0.04 * (n - 5)

    r_total = (r_single * k) / n
    meets_target = r_total <= target

    # Electrodes needed (UI logic)
    electrodes_needed = math.ceil(r_single * k / target)

    fault_current = 1000
    step_v = fault_current * r_total * 0.3
    touch_v = fault_current * r_total * 0.7

    return {
        'R_single': float(f"{r_single:.2f}"),
        'R_total': float(f"{r_total:.2f}"),
        'electrodesNeeded': int(electrodes_needed),
        'K_factor': float(f"{k:.2f}"),
        'meetsTarget': meets_target,
        'stepVoltage': float(f"{step_v:.2f}"),
        'touchVoltage': float(f"{touch_v:.2f}")
    }
