"""Phaxor — Sight Distance Engine (Python port)"""
import math

def solve_sight_distance(inputs: dict) -> dict | None:
    """Sight Distance Calculator."""
    V = float(inputs.get('V', 0))
    t = float(inputs.get('t', 2.5))
    f = float(inputs.get('f', 0.35))
    grade = float(inputs.get('grade', 0))
    dist_type = inputs.get('distType', 'ssd')

    if V <= 0:
        return None

    v_ms = V / 3.6
    g_pct = grade / 100.0

    # SSD
    d_reaction = v_ms * t
    denom = 2 * 9.81 * (f + g_pct)
    # Clamp braking distance to 0 if denom <= 0 (unsafe slope)
    d_braking = (v_ms ** 2) / denom if denom > 0 else float('inf')
    
    ssd = d_reaction + d_braking

    # ISD
    isd = 2 * ssd

    # OSD
    d1 = v_ms * t
    a_accel = 0.72 + 0.003 * V
    T_time = math.sqrt((4 * 15) / a_accel) if a_accel > 0 else 10.0
    d2 = v_ms * T_time + 0.5 * a_accel * (T_time ** 2)
    d3_ui = v_ms * t # Matching TS logic
    osd = d1 + d2 + d3_ui

    primary_dist = ssd
    label = 'Stopping Sight Distance'
    if dist_type == 'osd':
        primary_dist = osd
        label = 'Overtaking Sight Distance'
    elif dist_type == 'isd':
        primary_dist = isd
        label = 'Intermediate Sight Distance'

    r_min = (ssd ** 2) / (8 * (1.05 + 0.6))

    return {
        'ssd': float(f"{ssd:.2f}"),
        'osd': float(f"{osd:.2f}"),
        'isd': float(f"{isd:.2f}"),
        'dReaction': float(f"{d_reaction:.2f}"),
        'dBraking': float(f"{d_braking:.2f}"),
        'primaryDist': float(f"{primary_dist:.2f}"),
        'label': label,
        'vMs': float(f"{v_ms:.2f}"),
        'Rmin': float(f"{r_min:.0f}"),
        'd1': float(f"{d1:.2f}"),
        'd2': float(f"{d2:.2f}"),
        'd3': float(f"{d3_ui:.2f}")
    }
