# benchmark.py

import time
import csv
import random

from linked_list import ll_insert, ll_find, ll_delete
from hash_table import make_table, ht_insert, ht_find, ht_delete
from bst import bst_insert, bst_find, bst_delete

def generate_records(n=10000):
    records = [(f"User_{i:05d}", str(random.randint(100000, 999999))) for i in range(n)]
    records_shuffled = records[:]
    random.shuffle(records_shuffled)
    records_sorted = sorted(records)
    return records_shuffled, records_sorted

def measure_insert_ll(records):
    head = None
    start = time.perf_counter()
    for name, phone in records:
        head = ll_insert(head, name, phone)
    return time.perf_counter() - start

def measure_insert_ht(records):
    table = make_table(2000)
    start = time.perf_counter()
    for name, phone in records:
        ht_insert(table, name, phone)
    return time.perf_counter() - start

def measure_insert_bst(records):
    root = None
    start = time.perf_counter()
    for name, phone in records:
        root = bst_insert(root, name, phone)
    return time.perf_counter() - start

def run_all():
    shuffled, sorted_data = generate_records()

    results = []

    for mode, data in [('shuffled', shuffled), ('sorted', sorted_data)]:
        # LinkedList
        t = measure_insert_ll(data)
        results.append(["LinkedList", mode, "insert", t])

        # HashTable
        t = measure_insert_ht(data)
        results.append(["HashTable", mode, "insert", t])

        # BST
        t = measure_insert_bst(data)
        results.append(["BST", mode, "insert", t])

    with open("results.csv", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["Structure", "Mode", "Operation", "Time"])
        writer.writerows(results)

    print("Результаты сохранены в results.csv")

if __name__ == "__main__":
    run_all()
