import random
import time
import csv
import sys

sys.setrecursionlimit(20000)

def ll_insert(head, name, phone):
    data = {'name': name, 'phone': phone, "next": None}

    if head is None:
        return data

    current = head
    while current:
        if current['name'] == name:
            current['phone'] = phone
            return head
        if current['next'] is None:
            last = current
        current = current['next']

    last['next'] = data
    return head


def ll_find(head, name):
    current = head
    while current:
        if current['name'] == name:
            return current['phone']
        current = current['next']
    return None


def ll_delete(head, name):
    if head is None:
        return None

    if head['name'] == name:
        return head['next']

    prev = head
    current = head['next']
    while current:
        if current['name'] == name:
            prev['next'] = current['next']
            return head
        prev = current
        current = current['next']
    return head


def ll_list_all(head):
    data_list = []
    current = head
    while current:
        data_list.append({'name': current['name'], 'phone': current['phone']})
        current = current['next']
    data_list.sort(key=lambda x: x['name'])
    return data_list


def hash_function(name, size):
    return hash(name) % size


def ht_insert(buckets, name, phone):
    index = hash_function(name, len(buckets))
    head = buckets[index]
    new_head = ll_insert(head, name, phone)
    buckets[index] = new_head
    return buckets


def ht_find(buckets, name):
    index = hash_function(name, len(buckets))
    head = buckets[index]
    return ll_find(head, name)


def ht_delete(buckets, name):
    index = hash_function(name, len(buckets))
    head = buckets[index]
    new_head = ll_delete(head, name)
    buckets[index] = new_head
    return buckets


def ht_list_all(buckets):
    all_records = []
    for head in buckets:
        current = head
        while current is not None:
            all_records.append((current['name'], current['phone']))
            current = current['next']
    all_records.sort(key=lambda x: x[0])
    return all_records


def create_node(name, phone):
    return {'name': name, 'phone': phone, 'left': None, 'right': None}


def bst_insert(root, name, phone):
    if root is None:
        return create_node(name, phone)

    if name == root['name']:
        root['phone'] = phone
    elif name < root['name']:
        root['left'] = bst_insert(root['left'], name, phone)
    else:
        root['right'] = bst_insert(root['right'], name, phone)
    return root


def bst_find(root, name):
    if root is None:
        return None
    if name == root['name']:
        return root['phone']
    elif name < root['name']:
        return bst_find(root['left'], name)
    else:
        return bst_find(root['right'], name)


def find_min(node):
    while node['left'] is not None:
        node = node['left']
    return node


def bst_delete(root, name):
    if root is None:
        return None

    if name < root['name']:
        root['left'] = bst_delete(root['left'], name)
    elif name > root['name']:
        root['right'] = bst_delete(root['right'], name)
    else:
        if root['left'] is None:
            return root['right']
        if root['right'] is None:
            return root['left']

        min_node = find_min(root['right'])
        root['name'] = min_node['name']
        root['phone'] = min_node['phone']
        root['right'] = bst_delete(root['right'], min_node['name'])
    return root


def bst_list_all(root):
    result = []

    def inorder(node):
        if node is None:
            return
        inorder(node['left'])
        result.append((node['name'], node['phone']))
        inorder(node['right'])

    inorder(root)
    return result

def generate_records(n, seed=50): #почти в точности позаимствовано, просто понял что можно уже существующие в отдельный список заносить
    random.seed(seed)
    records = []
    for i in range(1, n + 1):
        name = f"User_{i:05d}"
        phone = "8" + ''.join(str(random.randint(0, 9)) for _ in range(10))
        records.append((name, phone))
    return records

def prepare_datasets(base_records):
    shuffled = base_records.copy()
    random.shuffle(shuffled)
    sorted_records = sorted(base_records, key=lambda x: x[0])
    return shuffled, sorted_records

def run_experiment(struct_funcs, records, mode_name, repeats=5):
    results = []
    for rep in range(repeats):
        struct = struct_funcs['create']()

        start = time.perf_counter()
        for name, phone in records:
            struct = struct_funcs['insert'](struct, name, phone)
        end = time.perf_counter()
        insert_time = end - start

        existing_names = [name for name, _ in records]
        sample_existing = random.sample(existing_names, 100)
        nonexistent = [f"None_{i}" for i in range(10)]
        search_names = sample_existing + nonexistent
        random.shuffle(search_names)

        start = time.perf_counter()
        for name in search_names:
            _ = struct_funcs['find'](struct, name)
        end = time.perf_counter()
        find_time = end - start

        to_delete = random.sample(existing_names, 10)
        start = time.perf_counter()
        for name in to_delete:
            struct = struct_funcs['delete'](struct, name)
        end = time.perf_counter()
        delete_time = end - start

        results.append({
            'structure': struct_funcs['name'],
            'mode': mode_name,
            'repetition': rep + 1,
            'insert_time': insert_time,
            'find_time': find_time,
            'delete_time': delete_time
        })
    return results

def main():
    N = 1000
    base_records = generate_records(N)
    shuffled, sorted_records = prepare_datasets(base_records)

    structures = {
        'LinkedList': {
            'name': 'LinkedList',
            'create': lambda: None,
            'insert': ll_insert,
            'find': ll_find,
            'delete': ll_delete,
            'list_all': ll_list_all
        },
        'HashTable': {
            'name': 'HashTable',
            'create': lambda: [None] * 10,
            'insert': ht_insert,
            'find': ht_find,
            'delete': ht_delete,
            'list_all': ht_list_all
        },
        'BST': {
            'name': 'BST',
            'create': lambda: None,
            'insert': bst_insert,
            'find': bst_find,
            'delete': bst_delete,
            'list_all': bst_list_all
        }
    }

    all_results = []
    repeats = 5

    for struct_name, funcs in structures.items():
        print(f"Тестирование {struct_name} на случайном порядке...")
        res = run_experiment(funcs, shuffled, 'random', repeats)
        all_results.extend(res)

        print(f"Тестирование {struct_name} на отсортированном порядке...")
        res = run_experiment(funcs, sorted_records, 'sorted', repeats)
        all_results.extend(res)

    with open('res.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['Structure', 'Mode', 'Repeat', 'Insert (sec)', 'Search (sec)', 'Delete (sec)'])
        for r in all_results:
            writer.writerow([
                r['structure'],
                r['mode'],
                r['repetition'],
                f"{r['insert_time']:.6f}",
                f"{r['find_time']:.6f}",
                f"{r['delete_time']:.6f}"
            ])

if __name__ == '__main__':
    main()