import csv
from statistics import mean

def run_experiments(maze_files, strategies, runs=5, out_csv="output/results.csv"):
    rows = []
    for maze_name, maze in maze_files.items():
        for strat_name, strat_cls in strategies.items():
            times = []
            visiteds = []
            lengths = []
            for _ in range(runs):
                solver = maze["solver_factory"](strat_cls())
                stats = solver.solve()
                times.append(stats.timeMs)
                visiteds.append(stats.visitedCells)
                lengths.append(stats.pathLength)
            rows.append({
                "maze": maze_name,
                "strategy": strat_name,
                "time_ms": round(mean(times), 3),
                "visited_cells": round(mean(visiteds), 1),
                "path_length": round(mean(lengths), 1)
            })

    with open(out_csv, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=["maze", "strategy", "time_ms", "visited_cells", "path_length"])
        writer.writeheader()
        writer.writerows(rows)

    return rows