import os
import time
import csv
from maze_builder import TextMazeBuilder
from pathfinding import BFSSearch, DFSSearch, AStarSearch
from solver import MazeSolver

def run_benchmark():

    data_dir = os.path.join(os.path.dirname(__file__), 'data')
    docs_dir = os.path.join(os.path.dirname(__file__), 'docs(results)')
    os.makedirs(docs_dir, exist_ok=True)
    
    mazes = {
        'small': 'small.txt',
        'medium': 'medium.txt',
        'large': 'large.txt'
    }
    
    strategies = {
        'BFS': BFSSearch(),
        'DFS': DFSSearch(),
        'A*': AStarSearch()
    }
    
    results = []
    builder = TextMazeBuilder()
    
    for name, fname in mazes.items():
        fpath = os.path.join(data_dir, fname)
        if not os.path.exists(fpath):
            print(f" {name}: не найден")
            continue
        
        maze = builder.load(fpath)
        print(f"\n{name} ({maze.width}x{maze.height})")
        
        for sname, strategy in strategies.items():
            times = []
            for _ in range(5):
                solver = MazeSolver(maze)
                solver.set_strategy(strategy)
                t0 = time.perf_counter()
                stats = solver.solve()
                t1 = time.perf_counter()
                times.append((t1 - t0) * 1000)
            
            avg = sum(times) / len(times)
            print(f"  {sname}: {avg:.3f}ms, visited={strategy.visited_count}, path={stats.path_length}")
            
            results.append({
                'maze': name,
                'strategy': sname,
                'time_ms': avg,
                'visited': strategy.visited_count,
                'path_len': stats.path_length
            })
    
    # Save CSV
    csv_path = os.path.join(docs_dir, 'results.csv')
    with open(csv_path, 'w', newline='', encoding='utf-8-sig') as f:
        writer = csv.DictWriter(f, fieldnames=['maze', 'strategy', 'time_ms', 'visited', 'path_len'])
        writer.writeheader()
        writer.writerows(results)
    
    print(f"\n Сохранено в {csv_path}")

if __name__ == "__main__":
    run_benchmark()