"""Phaxor — Weld Strength Engine (Python port)"""
import math

ELECTRODES = {
    'E60': {'label': 'E60xx', 'fexx': 414},
    'E70': {'label': 'E70xx (most common)', 'fexx': 482},
    'E80': {'label': 'E80xx', 'fexx': 552},
    'E90': {'label': 'E90xx', 'fexx': 621},
    'E100': {'label': 'E100xx', 'fexx': 690},
    'E110': {'label': 'E110xx', 'fexx': 758},
    'E120': {'label': 'E120xx', 'fexx': 827},
}

def solve_weld_strength(inputs: dict) -> dict | None:
    """Weld Strength Calculator (AWS D1.1)."""
    weld_type = inputs.get('weldType', 'fillet')
    leg_size = float(inputs.get('legSize', 0))
    weld_length = float(inputs.get('weldLength', 0))
    electrode_key = inputs.get('electrodeKey', 'E70')
    applied_force = float(inputs.get('appliedForce', 0))
    load_dir = inputs.get('loadDir', 'parallel')
    angle = float(inputs.get('angle', 0))

    if leg_size <= 0 or weld_length <= 0:
        return None

    electrode = ELECTRODES.get(electrode_key, ELECTRODES['E70'])
    fexx = electrode['fexx']

    throat = 0
    allowable_stress = 0

    if weld_type == 'fillet':
        throat = leg_size * 0.707
        allowable_stress = 0.30 * fexx
    elif weld_type == 'butt-full':
        throat = leg_size
        allowable_stress = 0.60 * fexx
    else:
        throat = leg_size * 0.707
        allowable_stress = 0.30 * fexx
    
    # Effective length
    effective_length = weld_length
    if weld_type == 'fillet':
        effective_length = max(weld_length - 2 * leg_size, weld_length * 0.9)
    
    throat_area = throat * effective_length
    
    # Direction factor
    direction_factor = 1.0
    if weld_type == 'fillet':
        if load_dir == 'transverse':
            direction_factor = 1.5
        elif load_dir == 'combined':
            rad = math.radians(angle)
            direction_factor = 1.0 + 0.5 * math.pow(math.sin(rad), 1.5)
            
    effective_allowable = allowable_stress * direction_factor
    effective_allowable_load = effective_allowable * throat_area

    actual_stress = applied_force / throat_area if throat_area > 0 else 0
    fos = effective_allowable / actual_stress if actual_stress > 0 else float('inf')
    efficiency = (effective_allowable_load / applied_force) * 100 if applied_force > 0 else 0

    weld_volume = 0
    if weld_type == 'fillet':
        weld_volume = 0.5 * leg_size * leg_size * weld_length
    else:
        weld_volume = leg_size * throat * weld_length

    return {
        'throatArea': float(f"{throat_area:.1f}"),
        'effectiveThroat': float(f"{throat:.2f}"),
        'allowableStress': float(f"{effective_allowable:.1f}"),
        'actualStress': float(f"{actual_stress:.1f}"),
        'allowableLoad': float(f"{effective_allowable_load:.1f}"),
        'fos': float(f"{fos:.2f}"),
        'efficiency': float(f"{efficiency:.1f}"),
        'weldVolume': float(f"{weld_volume:.1f}"),
        'safe': fos >= 1
    }
