def main():
    N = 10000
    random.seed(42)

    records_sorted = [(f"User_{i:05d}", f"8-999-123-{i:04d}") for i in range(N)]
    records_shuffled = records_sorted.copy()
    random.shuffle(records_shuffled)

    search_existing = [random.choice(records_sorted)[0] for _ in range(100)]
    search_non_existing = [f"None_{i}" for i in range(10)]
    search_names = search_existing + search_non_existing
    delete_names = [random.choice(records_sorted)[0] for _ in range(50)]

    csv_rows = [["Structure", "Mode", "Operation", "Time (sec)"]]
    plot_data = []

    def run_experiment(struct_type, mode, dataset):
        print(f"Start: {struct_type} | Mode: {mode}...")
        times_insert, times_find, times_delete = [], [], []

        for round_idx in range(1, 6):
            if struct_type == "LinkedList": container = None
            elif struct_type == "HashTable": container = ht_create(size=1000)
            elif struct_type == "BST": container = None

            # А. Вставка
            start = time.perf_counter()
            if struct_type == "LinkedList":
                for name, phone in dataset: container = ll_insert(container, name, phone)
            elif struct_type == "HashTable":
                for name, phone in dataset: ht_insert(container, name, phone)
            elif struct_type == "BST":
                for name, phone in dataset: container = bst_insert(container, name, phone)
            t_ins = time.perf_counter() - start
            times_insert.append(t_ins)
            csv_rows.append([struct_type, mode, f"insert (number {round_idx})", f"{t_ins:.6f}"])

            # Б. Поиск
            start = time.perf_counter()
            if struct_type == "LinkedList":
                for name in search_names: ll_find(container, name)
            elif struct_type == "HashTable":
                for name in search_names: ht_find(container, name)
            elif struct_type == "BST":
                for name in search_names: bst_find(container, name)
            t_find = time.perf_counter() - start
            times_find.append(t_find)
            csv_rows.append([struct_type, mode, f"find (number {round_idx})", f"{t_find:.6f}"])

            # В. Удаление
            start = time.perf_counter()
            if struct_type == "LinkedList":
                for name in delete_names: container = ll_delete(container, name)
            elif struct_type == "HashTable":
                for name in delete_names: ht_delete(container, name)
            elif struct_type == "BST":
                for name in delete_names: container = bst_delete(container, name)
            t_del = time.perf_counter() - start
            times_delete.append(t_del)
            csv_rows.append([struct_type, mode, f"delete (number {round_idx})", f"{t_del:.6f}"])

        # Запись средних значений
        csv_rows.append([struct_type, mode, "Insert (average)", f"{sum(times_insert)/5:.6f}"])
        csv_rows.append([struct_type, mode, "Find (average)", f"{sum(times_find)/5:.6f}"])
        csv_rows.append([struct_type, mode, "Delete (average)", f"{sum(times_delete)/5:.6f}"])

        avg_ins = sum(times_insert) / 5
        avg_find = sum(times_find) / 5
        avg_del = sum(times_delete) / 5

        plot_data.append((struct_type, mode, avg_ins, avg_find, avg_del))

    # Запуск всех тестов
    run_experiment("LinkedList", "random", records_shuffled)
    run_experiment("LinkedList", "sorted", records_sorted)
    run_experiment("HashTable", "random", records_shuffled)
    run_experiment("HashTable", "sorted", records_sorted)
    run_experiment("BST", "random", records_shuffled)
    run_experiment("BST", "sorted", records_sorted)

    # Сохранение в CSV
    with open("results.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerows(csv_rows)
    print("\n[Успех] Все тесты завершены! Результаты сохранены в 'results.csv'.")

    generate_performance_charts(plot_data)

if __name__ == '__main__':
    experiment_thread = threading.Thread(target=main)
    experiment_thread.start()
    experiment_thread.join()