"""Phaxor — Weir & Orifice Engine (Python port)"""
import math

def solve_weir_orifice(inputs: dict) -> dict | None:
    """Weir & Orifice Calculator."""
    w_type = inputs.get('type', 'rectangular')
    L = float(inputs.get('L', 0))
    H = float(inputs.get('H', 0))
    Cd = float(inputs.get('Cd', 0.62))
    theta = float(inputs.get('theta', 90))
    orifice_a = float(inputs.get('orificeA', 0))

    if H <= 0:
        return None

    g = 9.81
    Q = 0.0
    formula = ""

    if w_type == 'rectangular':
        Q = (2.0/3.0) * Cd * L * math.sqrt(2 * g) * (H ** 1.5)
        formula = 'Q = (2/3) * Cd * L * sqrt(2g) * H^(3/2)'
    elif w_type == 'v-notch':
        theta_rad = math.radians(theta / 2.0)
        Q = (8.0/15.0) * Cd * math.sqrt(2 * g) * math.tan(theta_rad) * (H ** 2.5)
        formula = 'Q = (8/15) * Cd * sqrt(2g) * tan(theta/2) * H^(5/2)'
    elif w_type == 'trapezoidal':
        Q = (2.0/3.0) * Cd * L * math.sqrt(2 * g) * (H ** 1.5)
        formula = 'Q = (2/3) * Cd * L * sqrt(2g) * H^(3/2) (Cipolletti)'
    elif w_type == 'broad-crested':
        Q = Cd * L * math.sqrt(g) * (H ** 1.5)
        formula = 'Q = Cd * L * sqrt(g) * H^(3/2)'
    elif w_type == 'orifice':
        Q = Cd * orifice_a * math.sqrt(2 * g * H)
        formula = 'Q = Cd * A * sqrt(2gH)'

    q_liters = Q * 1000.0
    
    va = 0.0
    if w_type != 'orifice' and L > 0:
        va = Q / (L * (H + 0.3))
    elif w_type == 'orifice': # or fallback
        va = Q / 0.1 # Very rough approx placeholder from TS

    return {
        'Q': float(f"{Q:.5f}"),
        'QLiters': float(f"{q_liters:.2f}"),
        'formula': formula,
        'Va': float(f"{va:.3f}")
    }
