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

from linked_list_phonebook import ll_insert, ll_find, ll_delete, ll_list_all
from hash_table_phonebook import ht_insert, ht_find, ht_delete, ht_list_all
from bst_phonebook import bst_insert, bst_find, bst_delete, bst_list_all

def generate_records(n, seed=42):
    random.seed(seed)
    records = []
    for i in range(1, n+1):
        name = f"User_{i:05d}"
        phone = f"{random.randint(100,999)}-{random.randint(1000,9999)}"
        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"NotExist_{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, 50)
        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 = 10000
    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"Testing {struct_name} on random order...")
        res_random = run_experiment(funcs, shuffled, 'random', repeats)
        all_results.extend(res_random)
        
        print(f"Testing {struct_name} on sorted order...")
        res_sorted = run_experiment(funcs, sorted_records, 'sorted', repeats)
        all_results.extend(res_sorted)
    
    with open('experiment_results.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}"
            ])
    
    print("Experiment finished. Results saved to experiment_results.csv")

if __name__ == '__main__':
    main()