import sys
import os
import time
import csv

# Добавляем родительскую папку в путь поиска
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from builders import TextFileMazeBuilder
from strategies import BFSStrategy, DFSStrategy, AStarStrategy

def run_experiment(maze_file, strategy, num_runs=5):
    """Запускает эксперимент для одной стратегии"""
    builder = TextFileMazeBuilder()
    
    # Корректируем путь к файлу лабиринта
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    maze_path = os.path.join(base_dir, maze_file)
    
    maze = builder.build_from_file(maze_path)
    
    times = []
    visited_counts = []
    path_length = 0
    
    for _ in range(num_runs):
        start_time = time.perf_counter()
        path = strategy.find_path(maze, maze.start, maze.exit)
        end_time = time.perf_counter()
        
        times.append((end_time - start_time) * 1000)  # в миллисекундах
        visited_counts.append(strategy.visited_count)
        if path:
            path_length = len(path)
    
    return {
        'maze': os.path.basename(maze_file),
        'strategy': strategy.name,
        'avg_time_ms': sum(times) / len(times),
        'min_time_ms': min(times),
        'max_time_ms': max(times),
        'avg_visited': sum(visited_counts) / len(visited_counts),
        'path_length': path_length
    }

def run_all_experiments():
    print("ЗАПУСК ЭКСПЕРИМЕНТОВ")
    
    mazes = [
        'mazes/simple_maze.txt',
        'mazes/small_maze.txt'
    ]
    
    strategies = [BFSStrategy(), DFSStrategy(), AStarStrategy()]
    
    results = []
    
    for maze_file in mazes:
        print(f"\nЛабиринт: {maze_file}")
        for strategy in strategies:
            print(f"  {strategy.name}...", end=" ", flush=True)
            result = run_experiment(maze_file, strategy)
            results.append(result)
            print(f"{result['avg_time_ms']:.2f} мс, посещено: {result['avg_visited']:.0f}")
    
    # Сохраняем результаты
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    results_dir = os.path.join(base_dir, 'docs', 'data')
    os.makedirs(results_dir, exist_ok=True)
    
    csv_path = os.path.join(results_dir, 'experiment_results.csv')
    with open(csv_path, 'w', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=['maze', 'strategy', 'avg_time_ms', 'min_time_ms', 'max_time_ms', 'avg_visited', 'path_length'])
        writer.writeheader()
        writer.writerows(results)
    print(f"Результаты сохранены в {csv_path}")
    
    # Вывод таблицы
    print("\nРЕЗУЛЬТАТЫ:")
    print(f"{'Лабиринт':<20} {'Стратегия':<10} {'Время(мс)':<12} {'Посещено':<10} {'Длина пути':<10}")
    for r in results:
        print(f"{r['maze']:<20} {r['strategy']:<10} {r['avg_time_ms']:>8.2f}    {r['avg_visited']:>8.0f}    {r['path_length']:>8}")
    
    return results

if __name__ == "__main__":
    run_all_experiments()