"""Phaxor — Gear Ratio Engine (Python port)"""

GEAR_TYPES = {
    'spur':      {'label': 'Spur Gear',      'efficiency': 98,  'maxRatio': 6},
    'helical':   {'label': 'Helical Gear',   'efficiency': 97,  'maxRatio': 10},
    'bevel':     {'label': 'Bevel Gear',     'efficiency': 97,  'maxRatio': 5},
    'worm':      {'label': 'Worm Gear',      'efficiency': 65,  'maxRatio': 100},
    'planetary': {'label': 'Planetary Gear', 'efficiency': 97,  'maxRatio': 12},
}

import math

def solve_gear_ratio(inputs: dict) -> dict:
    """Compute multi-stage gear train analysis."""
    n1 = inputs.get('inputSpeed', 0)
    T1 = inputs.get('inputTorque', 0)
    P_in = inputs.get('inputPower', 0)

    if P_in > 0 and n1 > 0 and T1 == 0:
        T1 = (P_in * 1000 * 60) / (2 * math.pi * n1)

    current_speed = n1
    current_torque = T1
    overall_ratio = 1
    overall_eff = 1
    stage_results = []

    for stage in inputs.get('stages', []):
        driver = stage.get('driverTeeth', 1)
        driven = stage.get('drivenTeeth', 1)
        ratio = driven / driver
        gt = GEAR_TYPES.get(stage.get('gearType', 'spur'), GEAR_TYPES['spur'])
        eff = gt['efficiency'] / 100
        mod = stage.get('module', 2)

        driven_speed = current_speed / ratio
        output_torque = current_torque * ratio * eff

        overall_ratio *= ratio
        overall_eff *= eff
        current_speed = driven_speed
        current_torque = output_torque

        stage_results.append({
            'ratio': ratio,
            'drivenSpeed': driven_speed,
            'outputTorque': output_torque,
            'efficiency': eff,
            'pitchDiaDriver': mod * driver,
            'pitchDiaDriven': mod * driven,
            'gearType': gt['label'],
            'overRatio': ratio > gt['maxRatio'],
        })

    input_power = T1 * (2 * math.pi * n1 / 60) / 1000 if n1 > 0 else 0

    return {
        'stageResults': stage_results,
        'overallRatio': overall_ratio,
        'overallEfficiency': overall_eff,
        'outputSpeed': current_speed,
        'outputTorque': current_torque,
        'speedReduction': ((n1 - current_speed) / n1 * 100) if n1 > 0 else 0,
        'inputPowerKW': input_power,
        'outputPowerKW': input_power * overall_eff,
        'torqueMultiplier': overall_ratio * overall_eff,
    }
