"""Benchmark helper for inference timing."""
import time
import numpy as np
from typing import Dict


def benchmark_inference(model_obj, runs: int = 50) -> Dict:
    """Run repeated inferences and return timing stats.

    model_obj must implement warmup() and run(inputs: dict) and expose backend.session/input_name.
    """
    # Build a dict of dummy inputs (one for each model input)
    inputs = {}
    try:
        sess = model_obj.backend.session
        for inp in sess.get_inputs():
            shape = [dim if isinstance(dim, int) else 1 for dim in inp.shape]
            inputs[inp.name] = np.random.rand(*shape).astype(np.float32)
    except Exception:
        # Fallback if we can't get model inputs
        inputs = {'input': np.random.rand(1, 3, 224, 224).astype(np.float32)}

    # warmup
    model_obj.warmup(3)

    times = []
    for _ in range(runs):
        start = time.perf_counter()
        try:
            model_obj.run(inputs)
        except Exception as e:
            print(f'Warning: benchmark run failed: {e}')
            pass
        times.append(time.perf_counter() - start)

    times = np.array(times)
    return {
        "runs": int(runs),
        "mean_s": float(times.mean()),
        "p50_s": float(np.percentile(times, 50)),
        "p90_s": float(np.percentile(times, 90)),
        "p99_s": float(np.percentile(times, 99)),
    }
