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

def solve_transformer(inputs: dict) -> dict | None:
    """Transformer Design Calculator."""
    rating = float(inputs.get('ratingVA', 0))
    vp = float(inputs.get('primaryVoltage', 0))
    vs = float(inputs.get('secondaryVoltage', 0))
    fe_loss = float(inputs.get('coreLoss', 0))
    cu_loss = float(inputs.get('copperLoss', 0))
    z_pct = float(inputs.get('percentImpedance', 0))

    if rating <= 0 or vp <= 0 or vs <= 0:
        return None

    turns_ratio = vp / vs
    ip = rating / vp
    is_sec = rating / vs

    def calc_eff(x, pf):
        out_p = rating * x * pf
        losses = fe_loss + (x * x * cu_loss)
        return (out_p / (out_p + losses)) * 100 if (out_p + losses) > 0 else 0

    eff_fl = calc_eff(1.0, 0.8)

    max_eff_load = math.sqrt(fe_loss / cu_loss) if cu_loss > 0 else 0
    max_eff_pct = calc_eff(max_eff_load, 0.8)

    # Voltage Regulation
    vr_lag = z_pct

    # All Day Efficiency
    # 12 hours at 50% load, 0.8 PF
    e_out = rating * 0.5 * 0.8 * 12
    e_cu = cu_loss * 0.25 * 12
    e_fe = fe_loss * 24
    all_day_eff = (e_out / (e_out + e_cu + e_fe)) * 100 if (e_out + e_cu + e_fe) > 0 else 0

    return {
        'turnsRatio': float(f"{turns_ratio:.2f}"),
        'Ip': float(f"{ip:.2f}"),
        'Is': float(f"{is_sec:.2f}"),
        'efficiencyFL': float(f"{eff_fl:.2f}"),
        'maxEffLoad': float(f"{max_eff_load:.4f}"),
        'maxEffPct': float(f"{max_eff_pct:.2f}"),
        'VR_lag': float(f"{vr_lag:.2f}"),
        'allDayEff': float(f"{all_day_eff:.2f}"),
        'losses': {
            'copper': cu_loss,
            'iron': fe_loss,
            'total': cu_loss + fe_loss
        }
    }
