#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import random
import csv
import sys
sys.setrecursionlimit(30000)

def ll_create_node(name, phone):
    return {'name': name, 'phone': phone, 'next': None}

def ll_insert(head, name, phone):
    if head is None:
        return ll_create_node(name, phone)
    
    if head['name'] == name:
        head['phone'] = phone
        return head
    
    current = head
    while current['next'] is not None:
        if current['next']['name'] == name:
            current['next']['phone'] = phone
            return head
        current = current['next']
    
    current['next'] = ll_create_node(name, phone)
    return head

def ll_find(head, name):
    current = head
    while current is not None:
        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']
    
    current = head
    while current['next'] is not None:
        if current['next']['name'] == name:
            current['next'] = current['next']['next']
            return head
        current = current['next']
    
    return head

def ll_list_all(head):
    records = []
    current = head
    while current is not None:
        records.append((current['name'], current['phone']))
        current = current['next']
    records.sort(key=lambda x: x[0])
    return records

def hash_function(name, table_size):
    return sum(ord(c) for c in name) % table_size

def ht_create_table(size=2000):
    return [None] * size

def ht_insert(table, name, phone):
    index = hash_function(name, len(table))
    table[index] = ll_insert(table[index], name, phone)

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

def ht_delete(table, name):
    index = hash_function(name, len(table))
    table[index] = ll_delete(table[index], name)

def ht_list_all(table):
    all_records = []
    for bucket in table:
        if bucket is not None:
            current = bucket
            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 bst_create_node(name, phone):
    return {'name': name, 'phone': phone, 'left': None, 'right': None}

def bst_insert(root, name, phone):
    if root is None:
        return bst_create_node(name, phone)
    
    current = root
    while True:
        if name < current['name']:
            if current['left'] is None:
                current['left'] = bst_create_node(name, phone)
                break
            else:
                current = current['left']
        elif name > current['name']:
            if current['right'] is None:
                current['right'] = bst_create_node(name, phone)
                break
            else:
                current = current['right']
        else:
            current['phone'] = phone
            break
    
    return root

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

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

def bst_delete(root, name):
    if root is None:
        return None
    
    parent = None
    current = root
    
    while current is not None and current['name'] != name:
        parent = current
        if name < current['name']:
            current = current['left']
        else:
            current = current['right']
    
    if current is None:
        return root
    
    if current['left'] is None or current['right'] is None:
        if current['left'] is not None:
            child = current['left']
        else:
            child = current['right']
        
        if parent is None:
            return child
        
        if parent['left'] == current:
            parent['left'] = child
        else:
            parent['right'] = child
    else:
        successor_parent = current
        successor = current['right']
        
        while successor['left'] is not None:
            successor_parent = successor
            successor = successor['left']
        
        current['name'] = successor['name']
        current['phone'] = successor['phone']
        
        if successor_parent['left'] == successor:
            successor_parent['left'] = successor['right']
        else:
            successor_parent['right'] = successor['right']
    
    return root

def bst_list_all(root):
    records = []
    stack = []
    current = root
    
    while stack or current is not None:
        while current is not None:
            stack.append(current)
            current = current['left']
        current = stack.pop()
        records.append((current['name'], current['phone']))
        current = current['right']
    
    return records

def generate_data(n=10000):
    records = [(f"User_{i:05d}", f"+7-999-{i:06d}") for i in range(n)]
    records_shuffled = records.copy()
    random.shuffle(records_shuffled)
    records_sorted = sorted(records, key=lambda x: x[0])
    return records_shuffled, records_sorted

def run_experiment(structure_name, insert_func, find_func, delete_func, 
                   list_all_func, init_func, records, n_find=100):
    
    data = init_func()
    names = [r[0] for r in records]
    
    start = time.perf_counter()
    for name, phone in records:
        if structure_name == "HashTable":
            insert_func(data, name, phone)
        else:
            data = insert_func(data, name, phone)
    insert_time = time.perf_counter() - start
    
    find_names = random.sample(names, min(n_find, len(names)))
    missing_names = [f"None_{i}" for i in range(10)]
    all_find_names = find_names + missing_names
    
    start = time.perf_counter()
    for name in all_find_names:
        if structure_name == "HashTable":
            find_func(data, name)
        else:
            find_func(data, name)
    find_time = time.perf_counter() - start
    
    delete_names = random.sample(names, min(50, len(names)))
    start = time.perf_counter()
    for name in delete_names:
        if structure_name == "HashTable":
            delete_func(data, name)
        else:
            data = delete_func(data, name)
    delete_time = time.perf_counter() - start
    
    return insert_time, find_time, delete_time

def main():
    print("Generating test data...")
    records_shuffled, records_sorted = generate_data(10000)
    
    results = []
    
    structures = [
        ("LinkedList", ll_insert, ll_find, ll_delete, ll_list_all, lambda: None),
        ("HashTable", ht_insert, ht_find, ht_delete, ht_list_all, lambda: ht_create_table(2000)),
        ("BST", bst_insert, bst_find, bst_delete, bst_list_all, lambda: None)
    ]
    
    for mode_name, records in [("random", records_shuffled), ("sorted", records_sorted)]:
        print(f"\nMode: {mode_name}")
        
        for struct_name, insert_f, find_f, delete_f, list_f, init_f in structures:
            print(f"  Testing {struct_name}...")
            
            times = []
            for run in range(5):
                insert_t, find_t, delete_t = run_experiment(
                    struct_name, insert_f, find_f, delete_f, list_f, init_f, records
                )
                times.append((insert_t, find_t, delete_t))
                print(f"    Run {run+1}: insert={insert_t:.4f}s, find={find_t:.4f}s, delete={delete_t:.4f}s")
            
            avg_insert = sum(t[0] for t in times) / 5
            avg_find = sum(t[1] for t in times) / 5
            avg_delete = sum(t[2] for t in times) / 5
            
            results.append([struct_name, mode_name, "insert", avg_insert])
            results.append([struct_name, mode_name, "find", avg_find])
            results.append([struct_name, mode_name, "delete", avg_delete])
    
    with open("results.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["Structure", "Mode", "Operation", "Time_seconds"])
        writer.writerows(results)
    
    print("\n" + "="*60)
    print("RESULTS (average over 5 runs):")
    print("="*60)
    for row in results:
        print(f"{row[0]:12} | {row[1]:8} | {row[2]:8} | {row[3]:.6f} sec")
    
    print("\nResults saved to results.csv")

if __name__ == "__main__":
    main()