"""Phaxor — Power Factor Correction Engine (Python port)"""
import math

def solve_pf_correction(inputs: dict) -> dict | None:
    """PF Correction Calculator."""
    kw = float(inputs.get('powerKW', 0))
    pf1 = float(inputs.get('currentPF', 0.7))
    pf2 = float(inputs.get('targetPF', 0.95))
    v = float(inputs.get('voltage', 415))
    phase = str(inputs.get('phase', '3'))
    freq = float(inputs.get('frequency', 50))

    if kw <= 0 or v <= 0:
        return None

    pf1 = max(0.01, min(0.99, pf1))
    pf2 = max(pf1 + 0.01, min(1.0, pf2))

    phi1 = math.acos(pf1)
    phi2 = math.acos(pf2)

    q1 = kw * math.tan(phi1)
    q2 = kw * math.tan(phi2)
    qc = q1 - q2

    s1 = kw / pf1
    s2 = kw / pf2

    mult = math.sqrt(3) if phase == '3' else 1.0
    i1 = (s1 * 1000.0) / (v * mult)
    i2 = (s2 * 1000.0) / (v * mult)

    reduction = ((i1 - i2) / i1) * 100 if i1 > 0 else 0

    omega = 2 * math.pi * freq
    cap_uf = (qc * 1000.0) / (v * v * omega) * 1e6 if (v * v * omega) > 0 else 0

    return {
        'Q1': float(f"{q1:.2f}"),
        'Q2': float(f"{q2:.2f}"),
        'Qc': float(f"{qc:.2f}"),
        'S1': float(f"{s1:.2f}"),
        'S2': float(f"{s2:.2f}"),
        'I1': float(f"{i1:.2f}"),
        'I2': float(f"{i2:.2f}"),
        'currentReduction': float(f"{reduction:.2f}"),
        'capUF': float(f"{cap_uf:.1f}"),
        'phi1': float(f"{phi1:.4f}"),
        'phi2': float(f"{phi2:.4f}")
    }
