"""Phaxor — Rankine Cycle Engine (Python port)"""
import math

def solve_rankine_cycle(inputs: dict) -> dict | None:
    """Rankine Cycle Calculator."""
    boiler_p = float(inputs.get('boilerP', 80))
    condenser_p = float(inputs.get('condenserP', 0.08))
    superheat = float(inputs.get('superheat', 100))
    power_mw = float(inputs.get('powerMW', 100))
    turb_eff = float(inputs.get('turbEff', 0.88))
    pump_eff = float(inputs.get('pumpEff', 0.85))

    if boiler_p <= condenser_p or power_mw <= 0:
        return None

    def sat_props(p_bar):
        tsat = 100 * ((p_bar / 1.013) ** 0.25)
        hf = 417 + 4.0 * (tsat - 100)
        hfg = 2257 - 1.8 * (tsat - 100)
        hg = hf + max(hfg, 500)
        sf = 1.303 + 0.003 * (tsat - 100)
        sfg = 6.048 - 0.012 * (tsat - 100)
        sg = sf + max(sfg, 1)
        return {'Tsat': tsat, 'hf': hf, 'hfg': hfg, 'hg': hg, 'sf': sf, 'sfg': sfg, 'sg': sg}

    boiler = sat_props(boiler_p)
    condenser = sat_props(condenser_p)

    # 3: Turbine Inlet
    cp_steam = 2.1
    h3 = boiler['hg'] + cp_steam * superheat
    t3_k = boiler['Tsat'] + superheat + 273.15
    t_sat_boiler_k = boiler['Tsat'] + 273.15
    s3 = boiler['sg'] + cp_steam * math.log(t3_k / t_sat_boiler_k)

    # 4s: Isentropic
    x4s = (s3 - condenser['sf']) / (condenser['sfg'] if condenser['sfg'] != 0 else 1)
    x4s = max(0.0, min(1.0, x4s))
    h4s = condenser['hf'] + x4s * condenser['hfg']

    # 4: Actual
    h4 = h3 - turb_eff * (h3 - h4s)

    # 1: Condenser Exit
    h1 = condenser['hf']
    s1 = condenser['sf']

    # 2: Pump
    vf = 0.001
    wp_s = vf * (boiler_p - condenser_p) * 100
    h2 = h1 + wp_s / pump_eff

    w_turbine = h3 - h4
    w_pump = h2 - h1
    w_net = w_turbine - w_pump
    q_in = h3 - h2
    q_out = h4 - h1

    if w_net <= 0 or q_in <= 0: return None

    efficiency = (w_net / q_in) * 100
    back_work_ratio = (w_pump / w_turbine) * 100 if w_turbine > 0 else 0
    
    tl = condenser['Tsat'] + 273.15
    th = t3_k
    carnot_eff = (1 - tl / th) * 100

    steam_rate = 3600 / w_net
    heat_rate = 3600 / (efficiency / 100)
    mass_flow = (power_mw * 1000) / w_net

    return {
        'h1': float(f"{h1:.1f}"), 'h2': float(f"{h2:.1f}"), 
        'h3': float(f"{h3:.1f}"), 'h4': float(f"{h4:.1f}"),
        's1': float(f"{s1:.3f}"), 's3': float(f"{s3:.3f}"),
        'wTurbine': float(f"{w_turbine:.1f}"),
        'wPump': float(f"{w_pump:.1f}"),
        'wNet': float(f"{w_net:.1f}"),
        'qIn': float(f"{q_in:.1f}"),
        'efficiency': float(f"{efficiency:.2f}"),
        'carnotEff': float(f"{carnot_eff:.2f}"),
        'massFlow': float(f"{mass_flow:.2f}")
    }
